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;

在線演示

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