Integer
Less than 1 minuteTC-Medium
Integer
Problem
Please complete type Integer<T>, which takes a type T and returns the integer part.
type Res1 = Integer<1> // 1
type Res2 = Integer<1.1> // 1
type Res3 = Integer<1.9> // 1
type Res4 = Integer<-1.9> // -1
type Res5 = Integer<'string'> // neverSolution
type Integer<T extends number | string> =
`${T}` extends `${infer Int}.${string}`
? Int extends `${infer N extends number}`
? N
: never
: `${T}` extends `${infer N extends number}`
? N
: neverHow it works:
- Convert
Tto a string template literal. - If it contains a
., the part before the dot is the integer portion. - If no
., the number is already an integer — return it as-is. - Use
infer N extends number(TS 4.8+) to parse the string fragment back to a numeric type. - Non-numeric strings like
'string'fail the pattern match and returnnever.
Key Takeaways
- Template literal
\${T}`` converts both numbers and numeric strings to a string for pattern matching. infer N extends numberis the idiomatic way to parse a numeric string back to a number type.- Splitting on
.gives the integer and fractional parts without any arithmetic.
