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

问题描述 投票:0回答:2

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

我想知道您将如何迭代该类型?

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

您是否应该以其他方式重新定义类型?

names.forEach(value => {
  console.log(value);
}); 
typescript
2个回答
1
投票

类型在编译后的代码中不存在-没有要迭代的内容。

如果您需要问题[[和中所示的联合类型,则需要能够将其作为数组进行迭代,请首先创建数组as const,然后将类型定义为数组的值:

const arr = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'] as const; export type names = typeof arr[number]; for (const num of arr) { console.log(num); }

1
投票
您可以将其定义为const和类似这样的类型:

const names = ['n1' , 'n2' , 'n3' , 'n4' , 'n5' , 'n6'] as const; type names = typeof names[number]; const name: names = 'n1'; console.log(names, name, names.forEach(name => name));

© www.soinside.com 2019 - 2024. All rights reserved.