-
-
Notifications
You must be signed in to change notification settings - Fork 546
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Addition
And Subtraction
Type Proposal
#774
Comments
What's the real-world use-case for this? |
When subtracting/adding numbers typescript looses all specific information which number it is, so const list = [1, 2, 3,] as const;
const element = list[3 - 1];
// TS doesn't now that 3-1 is two so the type of element is 1 | 2 | 3
type demonstration = typeof list[3 - 1]
// Error: Tuple type 'readonly [1, 2, 3]' of length '3' has no element at index '3'.
// There is no subtraction on a type level
type demonstration2 = typeof[Subtract<3, 1>]
// would be 3
// get an element of a list by index but with an offset
const offset = 2
const index = 0
const offsetedElement = list[offset + index]
// Again of type 1 | 2 | 3 |
And also for recursive types it can be quite useful to have a counter (This type makes it possible to mimic a for loop on a type level). Here is another code example in which i used the type AppendString<T extends string, S extends string> = `${T}${S}`;
type RepeatString<
S extends string,
N extends number,
Counter extends number = 0,
TotalString extends string = "",
> = Counter extends N
? TotalString
: RepeatString<S, N, Add<Counter, 1>, AppendString<TotalString, S>>; And here is an example of using the type LengthOfString<
T extends string,
N extends number = 0,
> = T extends `${infer R}${infer L}` ? LengthOfString<L, Add<N, 1>> : N; |
These were added in https://github.com/sindresorhus/type-fest/releases/tag/v4.12.0
|
Typescript doesn't support arithmetic operators on a type level.
I suggest introducing new types for Addition and Subtraction
I've semi successfully implemented these types already as they can be seen in this Gist.
Especially a type for addition can be very useful to create recursive types.
Upvote & Fund
The text was updated successfully, but these errors were encountered: