LoginSignup
0
0

More than 1 year has passed since last update.

西暦日付に型定義

Last updated at Posted at 2021-05-27

Date は エラーになるが stringよりは狭まったものがほしい

TL;DR;

const oneToNine = [1, 2, 3, 4, 5, 6, 7, 8, 9] as const;
const d = [0, ...oneToNine] as const;
type OneToNine = typeof oneToNine[number];
type D = typeof d[number];
type YYYY = `19${D}${D}` | `20${D}${D}`;
type MM = `0${OneToNine}` | `1${0 | 1 | 2}`;
type DD = `${0}${OneToNine}` | `${1 | 2}${D}` | `3${0 | 1}`;
// これを使う
export type DateYMDString = `${YYYY}/${MM}/${DD}`;

 2021-05-27 at 17.31.57.png

let sample1 : Date;
sample1 = '2021/05/27'
// => エラー
// Type 'string' is not assignable to type 'Date'

let sample1 : DateYMDString;
sample1 = '2021/05/27'
// => OK
sample1= '2020:05:27'
// => エラー
// Type '"2020:05:27"' is not assignable to type '"1900/01/01" | "1900/01/02" | "1900/01/03" | "1900/01/04" | "1900/01/05" | "1900/01/06" | "1900/01/07" | "1900/01/08" | "1900/01/09" | "1900/01/10" | "1900/01/11" | "1900/01/12" | ... 74387 more ... | "2099/12/31"'.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0