Implement BinaryToDecimal<S>
which takes an exact string type S
consisting 0 and 1 and returns an exact number type corresponding with S
when S
is regarded as a binary. You can assume that the length of S
is equal to or less than 8 and S
is not empty.
type Res1 = BinaryToDecimal<'10'>; // expected to be 2
type Res2 = BinaryToDecimal<'0011'>; // expected to be 3
/* _____________ Your Code Here _____________ */
type NumberToArray<T extends number, R extends 1[] = []> = R['length'] extends T ? R : NumberToArray<T, [...R, 1]>;
type GetTwice<T extends unknown[]> = [...T, ...T];
type BinaryToDecimal<S extends string, Result extends unknown[] = []> = S extends `${infer First extends number}${infer RT}`
? BinaryToDecimal<RT, [...GetTwice<Result>, ...NumberToArray<First>]>
: Result['length'];
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<BinaryToDecimal<'10'>, 2>>,
Expect<Equal<BinaryToDecimal<'0011'>, 3>>,
Expect<Equal<BinaryToDecimal<'00000000'>, 0>>,
Expect<Equal<BinaryToDecimal<'11111111'>, 255>>,
Expect<Equal<BinaryToDecimal<'10101010'>, 170>>,
]
标签:Binary,NumberToArray,Typescript,_____________,Decimal,extends,Expect,type,Binary From: https://www.cnblogs.com/Answer1215/p/16945728.html