以下是我想要实现的目标:
const names = ["foo", "bar", "baz"]; type NameType = elementof names; // This is not valid TypeScript
行为与此相同:
type NameType = "foo" | "bar" | "baz";
解决方案需要完成几件事。
TypeScript能做到这一点吗?
注: 这与 Convert string[] literal to string type literal ,因为这个问题不需要特定的字符串序列。联合类型不会在运行时生成任何获取订单信息的方法。
可以使用类型查询获取项目的类型:
type NameType = typeof names[number];
问题是 names 是 string[] ,所以上面的代码只生成 string .
names
string[]
string
可以推断 const 使用辅助函数。
const
function array<T extends string>(p: T[]) : T[] { return p } const names = array(["foo", "bar", "baz"]); type NameType = typeof names[number]; // The same as "foo" | "bar" | "baz"