我们的工作中有这个代码,我想知道它和手动输入相同内容之间的区别。
const tuple = <T extends string[]>(...args: T) => args; const strings = tuple( 'blabla', 'default', 'standard' ); export type Strings = typeof strings[number];
当我把鼠标悬停在“字符串”上时,它基本上是 type Strings = 'blabla' | 'default' | 'standard'
type Strings = 'blabla' | 'default' | 'standard'
我的问题是,为什么不简单地输入相同的内容呢?
type Strings = 'blabla' | 'default' | 'standard';
而不是所有的元组?我看不出有什么不同,但如果有人能解释为什么我们要使用这个元组函数,那就太好了
如果你不出口 strings 那么直接声明类型肯定更好。但在某些情况下,您还需要这些值,并使用它们 tuple 函数使您无需对每个函数指定两次。
strings
tuple
不过,有一种更简单、更安全的方法:
export const strings = [ 'blabla', 'default', 'standard' ] as const; // type: readonly ["blabla", "default", "standard"] export type Strings = typeof strings[number] // type Strings = "blabla" | "default" | "standard"
这使得 串 只读,所以你不能做一个不健全的 strings.pop() 例如
串
strings.pop()
TypeScript playground