如何在 TypeScript 中为可索引类型的键创建字符串文字类型?

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

我在 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;

这可能吗?

typescript union string-literals
1个回答
-2
投票

在 TypeScript 中,您可以通过结合使用 keyof 运算符和 type 关键字来为可索引类型的键创建字符串文字类型。

举个例子:

type MyIndexableType = {
  [key: string]: number;
};

type MyIndexableTypeKeys = keyof MyIndexableType;

// MyIndexableTypeKeys is now a string literal type that can only contain
// the keys of MyIndexableType, which are strings.

在这个例子中,我们首先定义了一个可索引类型MyIndexableType,它将字符串映射到数字。然后,我们使用 keyof 运算符创建一个字符串文字类型 MyIndexableTypeKeys,它只能包含 MyIndexableType 的键。

您可以使用此字符串文字类型来强制在索引到您的可索引类型时仅使用有效键,并在您的编辑器中获得自动完成和类型检查支持。

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