我在 TypeScript 中有一个可索引类型,其键可以是字符串或数字,如下所示:
export type MyRecords = { [name: string]: string | number };
const myRecords: MyRecords = {
foo: 'a',
bar: 1,
};
我想创建一个仅包含该类型字符串键的字符串文字类型,以便我可以使用它来确保代码中的类型安全。例如:
type KeysOfMyRecords = /* ??? */;
const key: KeysOfMyRecords = 'foo'; // should be OK
const invalidKey: KeysOfMyRecords = 'invalid'; // should cause a error
我尝试了以下方法但没有成功:
type KeysOfMyRecords = keyof typeof myRecords;
这可能吗?
最佳答案
我认为你可以使用泛型来实现这一点:
export type MyRecords<T extends string | number | symbol> = Record<T, string | number>
const myRecords : MyRecords<'foo' | 'bar'>= {
foo: 'a',
bar: 1,
};
type KeysOfMyRecords = keyof typeof myRecords;
const key: KeysOfMyRecords = 'foo'; // should be OK
const invalidKey: KeysOfMyRecords = 'invalid'; // should cause a error
正如您在上面看到的缺点是,您在定义对象时必须提及键。
您期望的问题是我们希望 myRecords
属于某种类型 MyRecords
。现在我们已经明确定义了 MyRecords 类型,以字符串作为键,这意味着任何字符串。我们也可以直接在代码中使用 const
断言,但它不能保证 MyRecords
类型的类型安全。
关于typescript - 如何在 TypeScript 中为可索引类型的键创建字符串文字类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76157070/