gpt4 book ai didi

typescript - 需要特定字符串作为 TypeScript 接口(interface)中的可选键

转载 作者:行者123 更新时间:2023-12-02 16:37:00 26 4
gpt4 key购买 nike

我有一种情况,我可以将一些可选的、T 恤尺码的 Prop 添加到一个对象中。有没有办法定义一个类型并将其设置为接口(interface)中可选键的类型?

type Size = `xxs` | `xs` | `s` | `m` | `l` | `xl` | `xxl`;

interface Sizes {
[key: Size]: string;
^^^
}

上面的例子向我展示了以下错误:

An index signature parameter type cannot be a union type. Consider using a mapped object type instead.ts(1337)

然后我找到了this question ,并修改我的代码如下:

type Size = `xxs` | `xs` | `s` | `m` | `l` | `xl` | `xxl`;

interface Sizes {
[key in Size]: string;
^^^^^^^^^^^
}

但随后出现以下错误:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

Cannot find name 'key'.ts(2304)

在我的实现过程中,我显然遗漏了一些相当重要的东西。任何解释将不胜感激。

最佳答案

A mapped type不是接口(interface)。你可以把它变成 type alias而不是界面:

type TSizes = { [K in Size]?: string };

请注意,我将 ? 放在那里,这使得属性成为可选的,正如您可能想要的那样。

一旦你有了这样一个命名类型,你就可以创建一个扩展它的接口(interface)(因为它的所有属性名称都是静态已知的):

interface ISizes extends TSizes { }

或者您可以使用内置的 PartialRecord同时执行这两项操作的实用程序类型:

interface Sizes extends Partial<Record<Size, string>> { }

然后,Sizes 是一个接口(interface),带有来自 Size 的可选属性键,其值是 string 类型:

const s: Sizes = {
s: "foo",
m: "bar",
xxl: "bazzz"
}

好的,希望对你有帮助;祝你好运!

Playground link to code

关于typescript - 需要特定字符串作为 TypeScript 接口(interface)中的可选键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62525903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com