We have this code at our work, which i wanted to know the difference between it and just manually typing out the same thing.
const tuple = <T extends string[]>(...args: T) => args;
const strings = tuple(
'blabla',
'default',
'standard'
);
export type Strings = typeof strings[number];
When i hover over "Strings", it basically is type Strings = 'blabla' | 'default' | 'standard'
My question is, why not just simply type out the samething?
type Strings = 'blabla' | 'default' | 'standard';
Instead of all the tuple stuff? I can't see a difference, but if someone could explain why we're using this Tuple function that would be great
CodePudding user response:
If you don't export strings
then it is definitely better to directly declare the type. In some cases you also need the values though, and using that tuple
function saves you from having to specify each one twice.
There's a simpler and safer way to do this though:
export const strings = [ 'blabla', 'default', 'standard' ] as const;
// type: readonly ["blabla", "default", "standard"]
export type Strings = typeof strings[number]
// type Strings = "blabla" | "default" | "standard"
This makes strings
readonly, so you can't do an unsound strings.pop()
for example.