如何迭代打字稿字符串文字?

sre*_*moh 2 typescript

我有这个文字类型export type names = 'n1' | 'n2' | 'n3' | 'n4' | 'n5' | 'n6';

我想知道你会如何迭代该类型?

也许您可以将该类型转换为其他类型并进行迭代?

您应该以不同的方式重新定义类型吗?

names.forEach(value => {
  console.log(value);
}); 
Run Code Online (Sandbox Code Playgroud)

Sha*_*tin 8

简答

您可以将其定义为 const 和类型,如下所示:

const names = ['n1' , 'n2' , 'n3' , 'n4' , 'n5' , 'n6'] as const;

// This produces the union type 'n1' | 'n2' | 'n3' | 'n4' | 'n5' | 'n6';
type names = typeof names[number];

// use names as a type here
const n1: names = 'n1';

console.log({
  names,
  n1,
  // use names as an array here
  mapped: names.map(name => `I am ${name}`)
});
Run Code Online (Sandbox Code Playgroud)

解释和演示

这里发生了什么?

创建一个带有const context 的as const数组。这意味着该数组不是数组,而是特定字符串文字值的只读数组。string

然后,typeof names[number]使用索引访问运算符将这些字符串文字值提取到联合类型中。

如果我们没有使用as const来定义数组,那么typeof names[number]将为我们提供string类型而不是数组字符串文字值的并集。

最终结果非常整洁。我们可以用作names联合类型进行类型检查,并在运行时用作数组。

位于 Playground 中,这是 JavaScript 中的 Playground 输出:

const names = ['n1' , 'n2' , 'n3' , 'n4' , 'n5' , 'n6'] as const;

// This produces the union type 'n1' | 'n2' | 'n3' | 'n4' | 'n5' | 'n6';
type names = typeof names[number];

// use names as a type here
const n1: names = 'n1';

console.log({
  names,
  n1,
  // use names as an array here
  mapped: names.map(name => `I am ${name}`)
});
Run Code Online (Sandbox Code Playgroud)

警告:使用names联合类型和数组值会引发有关命名约定的问题。通常,类型采用 PascalCased(例如Names),值采用驼峰命名法(例如names)。我们应该遵循哪些命名约定?

为了完整起见,以下是两个文件在 VS Code 中的外观:

在此输入图像描述