[Typescript] 152 Medium - IsOdd

Zhentiw發表於2024-05-15

return true is a number is odd

/* _____________ Your Code Here _____________ */

type LastChar<T extends string> =  T extends `${infer First}${infer Rest}` 
    ? Rest extends ""
      ? First
      : LastChar<Rest>
    : never;
type IsOdd<T extends number> = `${T}` extends `${infer _}.${infer __}` 
  ? false 
  :`${T}` extends `${infer _}e${infer __}` 
    ? false
    : LastChar<`${T}`> extends '1' | '3' | '5' | '7' | '9' 
      ? true 
      : false; 

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<IsOdd<5>, true>>,
  Expect<Equal<IsOdd<2023>, true>>,
  Expect<Equal<IsOdd<1453>, true>>,
  Expect<Equal<IsOdd<1926>, false>>,
  Expect<Equal<IsOdd<2.3>, false>>,
  Expect<Equal<IsOdd<3e23>, false>>,
  Expect<Equal<IsOdd<number>, false>>,
]

相關文章