Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

9155 - ValidDate #11787

Open
darkyzhou opened this issue Jun 17, 2022 · 0 comments
Open

9155 - ValidDate #11787

darkyzhou opened this issue Jun 17, 2022 · 0 comments
Labels
9155 answer Share answers/solutions to a question en in English

Comments

@darkyzhou
Copy link

darkyzhou commented Jun 17, 2022

Other solutions mainly use union types of string literals, I find it feasible to solve the problem without them:

type ValidDate<T extends string> = T extends `${infer M1}${infer M2}${infer D1}${infer D2}${infer Rest}` ? Rest extends '' ?
  `${M1}${M2}` extends keyof MonthDays ?
    `${D1}${D2}` extends '00' ? false :
      InRange<MonthDays[`${M1}${M2}`], `${D1}${D2}`>
  : false
: false : false;

type MonthDays = {
  '01': '31',
  '02': '28',
  '03': '31',
  '04': '30',
  '05': '31',
  '06': '30',
  '07': '31',
  '08': '31',
  '09': '30',
  '10': '31',
  '11': '30',
  '12': '31',
}

type GreaterMap = {
  '0': [],
  '1': ['0'],
  '2': ['1', '0'],
  '3': ['2', '1', '0'],
  '4': ['3', '2', '1', '0'],
  '5': ['4', '3', '2', '1', '0'],
  '6': ['5', '4', '3', '2', '1', '0'],
  '7': ['6', '5', '4', '3', '2', '1', '0'],
  '8': ['7', '6', '5', '4', '3', '2', '1', '0'],
  '9': ['8', '7', '6', '5', '4', '3', '2', '1', '0'],
}

type Greater<A extends string, B extends string> = A extends keyof GreaterMap ? Contains<B, GreaterMap[A]> : never;
type Contains<B extends string, ARR extends any[]> = ARR extends [infer Head, ...infer Rest] ?
  Eq<B, Head> extends true ? true : Contains<B, Rest>
: false;
type GreaterOrEq<A extends string, B extends string> = Greater<A, B> extends true ? true : Eq<A, B>;
type Eq<A extends any, B extends any> = A extends B ? B extends A ? true : false : false;

type InRange<R extends string, T extends string> = R extends `${infer R1}${infer R2}` ?
  T extends `${infer T1}${infer T2}` ?
    Greater<R1, T1> extends true ? true : Eq<R1, T1> extends true ? GreaterOrEq<R2, T2> : false
  : never
: never;
@darkyzhou darkyzhou added answer Share answers/solutions to a question en in English labels Jun 17, 2022
@github-actions github-actions bot added the 9155 label Jun 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
9155 answer Share answers/solutions to a question en in English
Projects
None yet
Development

No branches or pull requests

1 participant