Typescript类型体操 - Absolute

题目

中文

实现一个接收string,number或bigInt类型参数的Absolute类型,返回一个正数字符串。

例如

type Test = -100;
type Result = Absolute<Test>; // expected to be "100"

English

Implement the Absolute type. A type that take string, number or bigint. The output should be a positive number string

For example

type Test = -100;
type Result = Absolute<Test>; // expected to be "100"

答案

type Absolute<T extends number | string | bigint> = T extends `${'+' | '-'}${infer R}`
  ? R
  : (T extends string ? T : Absolute<`${T}`>);

在线演示

posted @ 2022-09-06 21:12  Laggage  阅读(43)  评论(0编辑  收藏  举报