-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Support inferring numeric literal types from their string representations #42938
Comments
This isn't really going to do what you want because intersection inference deliberately discards "matching" constituents. e.g. type Disposable = { dispose(): void };
type FooDisp = { foo: string } & Disposable
declare function nondisposable<T>(arg: T & Disposable): T;
declare const fd: FooDisp
// p: { foo: string }
const p = nondisposable(fd); I would probably write this as type Converter<D extends number> = D extends unknown ? [`${D}`, D] : never;
type Convert = Converter<0 | 1 | 2 | 3 /* etc to some reasonable number */>;
type Match<T, U> = T extends [U, infer V] ? V : never;
type ToNumber<T extends string> = Match<Convert, T>;
const foo: ToNumber<'1'> = 1 // OK |
This sounds more like a suggestion that we should support the pattern |
Is this the official place to 👍 a request for type StrToNum<S extends string> = ✨🧙♀️🧙♂️✨ which is the inverse of type NumToStr<N extends number> = `${N}`; ? If so, 👍! |
Hello, thank you for your work on TypeScript. Do you have an update on this opinion now with the release of the new recursion improvements? It is now possible to create N-sized addition, subtraction, ect. types that manipulate using string types. I have done this and my integer addition type works for numbers from |
Can this issue be closed, as the desired feature was introduced in #48094? |
yes it can. for the record here's how to create the type ToNumber<T extends string> = T extends `${infer Result extends number}`? Result: never |
Bug Report
🔎 Search Terms
infer conditional type intersection
🕗 Version & Regression Information
4.3.0-dev.20210224
Playground link with relevant code
💻 Code
🙁 Actual behavior
T
doesn't extend${number & infer R}
, even though it does extend${number & any}
🙂 Expected behavior
T
should extend${number & infer R}
and (if my understanding ofinfer
is correct)R
should be1
The text was updated successfully, but these errors were encountered: