Typescript类型体操 - Trunc

题目

中文

实现类型版本的 Math.trunc, 其接受一个字符串或数字作为泛型参数, 并返回移除了全部小数位部分后的整数

示例:

type A = Trunc<12.34>; // 12

English

Implement the type version of Math.trunc, which takes string or number and returns the integer part of a number by removing any fractional digits.

For example:

type A = Trunc<12.34>; // 12

答案

type Trunc<T extends string | number> = T extends number
    ? Trunc<`${T}`>
    : T extends `${infer L}.${any}`
    ? L
    : T;

在线演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章