我想从对象数组中生成类型.
const names = [
{
name: 'Bob'
},
{
name: 'Jane'
},
{
name: 'John'
},
{
name: 'Mike'
},
]
结果应该如下所示:
type NameType = 'Bob' | 'Jane' | 'John' | 'Mike'
我看到了很多参考资料,比如这个typescript-types-from-arrays
但这些示例始终使用字符串数组作为资源. 比如:
const array = ['one', 'two',...]
它工作得无懈可击.
但我想要做的是生成具有如下array.map
的类型:
const allNames = names.map((item) => item.name) as const;
type NameType = typeof names[number];
但这导致了一个:
A 'const' assertions can only be applied to references to
enum members, or string, number, boolean, array, or object literals.
下面是我try 做的一个可玩的例子: Stackblitz个
i want to use the function getName()
with IntelliSense to know which names are available in the names
array.
like this: