time{
HH:string
MM:string
}
Assume that there are objects such as , and that HH and MM are retrieved from the API as strings.
I would like HH and MM to be able to substitute only the zero embedded string numbers of '01'...'60'.
I don't like it because it contains un-filled strings and alphabets like HH: '1' or HH: 'aaaa' if I want to.
HH: '00' | '01' | '02' | '03' | ... | '58' | '59' | '60'
It's okay to write it by hand like this, but it doesn't look like TS, so I'd like to use the type variables and put them together in a short line somehow.
If you have any good ideas, please let me know.
The TS version is 3.9, but if there is a good way to write after 4.0, we are looking for mm
typescript
I think you can use Template literal types in TypeScript 4.1 and later features.It's not an official release yet, so you should try it on Playground.
You can use infer
to express boundaries strictly, but as a simple and intuitive example, you can use the following:
typeConcat<S1 extensions number,S2 extensions number>=`${S1}${S2}`;
type SingleDigitNumber = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type HH=Concat<0 | 1, SingleDigitNumber> |Concat<2,0 | 1 | 2 | 3 | 4 >;;
type MM = Concat<0 | 1 | 2 | 3 | 4 | 5, SingleDigitNumber > | "60";
interface Time {
hh —HH;
mm —MM;
}
const time : Time = {
hh —"12",
mm: "59",
};
© 2024 OneMinuteCode. All rights reserved.