Skip to content
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

Proposal: LiteralToPrimitive #338

Closed
jonahsnider opened this issue Jan 2, 2022 · 1 comment · Fixed by #340
Closed

Proposal: LiteralToPrimitive #338

jonahsnider opened this issue Jan 2, 2022 · 1 comment · Fixed by #340
Labels
enhancement New feature or request type addition

Comments

@jonahsnider
Copy link
Contributor

Description

Get the primitive type for a given literal.

type T = 123 | "hello"; // 123 | 'hello'
type U = LiteralToPrimitive<T>; // number | string

Would this be useful for others? If yes, I can create a pull request to implement it.

Example behavior

Literal type Resulting type
123 number
123n bigint
'hello' string
true boolean
undefined undefined
typeof sym where const sym = Symbol(); symbol
null null
anything else, including non-null objects never

Usage example

I find myself using types like this when the return type of a function is a generic type used in an argument.
For example, a sum function that works with numbers or bigints:

// TODO: Add other types
type LiteralToPrimitive<T> = T extends number ? number : T extends bigint ? bigint : never;

// declare function sum<T extends number | bigint>(x: T, y: T): T;
declare function sum<T extends number | bigint>(x: T, y: T): LiteralToPrimitive<T>;

sum(1n, 2n);
//^? bigint
sum(1, 2);
//^? number

The commented sum declaration is wrong, a return type of T would mean that sum(1, 2) would have a return type of 1 | 2.

Playground Link: Provided

Relevant reading

@sindresorhus
Copy link
Owner

Yeah, sounds useful in some cases.


Similar thing in an SO answer: https://stackoverflow.com/a/56333836/64949

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request type addition
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants