gcanti / typelevel-ts

Type level programming in TypeScript
https://gcanti.github.io/typelevel-ts
MIT License
357 stars 12 forks source link

add `NumberToString` conversion map #7

Closed amir-arad closed 7 years ago

amir-arad commented 7 years ago

useage:

type MyType<I extends number> = ... NumberToString[I]
gcanti commented 7 years ago

@amir-arad how do you use this type? I'm trying to do the following but got some errors (ts v2.4.2)

import { StringEq } from '../src'

export type NumberToString = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

// Type 'N' cannot be used to index type '["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]'
export type GetString<N extends number> = NumberToString[N]

// Type 'A' cannot be used to index type '["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]'.
// Type 'B' cannot be used to index type '["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]'.
export type NumberEq<A extends number, B extends number> = StringEq<NumberToString[A], NumberToString[B]>
amir-arad commented 7 years ago

I use it percisely to avoid such errors in different scenarios :)

declare type THListLengthNum<L extends THList> = {
    true: 0;
    false: Increment[THListLengthNum<THListTail<L>>];
}[THListIsTHNil<L>];
type Func<A extends THList, ...> = {
0:...
1:...
2:...
...
}[NumberToString[THListLengthNum<A>]];

were I to use [THListLengthNum<A>] in the last line I'd have gotten an error.

KiaraGrouwstra commented 7 years ago

Wow, I love the workaround. That hadn't occurred to me so far. I guess then its opposite StringToNumber may serve to resolve the same error for this one. Anyway, I'd filed this issue earlier at https://github.com/Microsoft/TypeScript/issues/15768.