You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeT=123|"hello";// 123 | 'hello'typeU=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 typestypeLiteralToPrimitive<T>=Textendsnumber ? number : Textendsbigint ? bigint : never;// declare function sum<T extends number | bigint>(x: T, y: T): T;declarefunctionsum<Textendsnumber|bigint>(x: T,y: T): LiteralToPrimitive<T>;sum(1n,2n);//^? bigintsum(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.
Description
Get the primitive type for a given literal.
Would this be useful for others? If yes, I can create a pull request to implement it.
Example behavior
123
number
123n
bigint
'hello'
string
true
boolean
undefined
undefined
typeof sym
whereconst sym = Symbol();
symbol
null
null
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
number
s orbigint
s:The commented
sum
declaration is wrong, a return type ofT
would mean thatsum(1, 2)
would have a return type of1 | 2
.Playground Link: Provided
Relevant reading
The text was updated successfully, but these errors were encountered: