元组与硬编码字符串
Tuple vs hard coded string
我们的工作中有这段代码,我想知道它与手动输入相同内容的区别。
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';
而不是所有元组的东西?我看不出有什么不同,但如果有人能解释为什么我们要使用这个 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
只读,所以你不能做一个不合理的 strings.pop()
例如。
我们的工作中有这段代码,我想知道它与手动输入相同内容的区别。
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';
而不是所有元组的东西?我看不出有什么不同,但如果有人能解释为什么我们要使用这个 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
只读,所以你不能做一个不合理的 strings.pop()
例如。