gpt4 book ai didi

reactjs - typescript 如何在对象中键入自定义键

转载 作者:行者123 更新时间:2023-12-04 13:31:14 25 4
gpt4 key购买 nike

我有一个这样的功能:

interface IUseTest {
settings: {
id: string
}
};

const useTest = (properties: IUseTest) => {
const { settings } = properties;

const test = (
item: {
[settings.id]: string | number, // Error here
[key: string]: any
}
): object => {
// function logic, doesn't matter
};

return {
test
};
};

我应该使用从设置对象中获得的必需键来设置一个项目,但出现错误:

A computed property name in a type literal must refer to an expressionwhose type is a literal type or a 'unique symbol' type.


我该怎么办?
更新:有没有办法不使用接口(interface)?
更新:项目可以是这样的: { id: 'someId' }{ key: 'someKey' } 更新: typescript 的版本是 4.0.3

最佳答案

您可以使用泛型和 Mapped Types ,像这样:

interface IUseTest<T extends string> {
settings: {
id: T
}
};

const useTest = <T extends string>(properties: IUseTest<T>) => {
const { settings } = properties;

const test = (
item: { [settingsId in T]: string | number } & {
[key: string]: any
}
): object => {
// function logic, doesn't matter
};

return {
test
};
};
在这里, <T>是泛型和 { [settingsId in T]: string | number }是映射类型。

关于reactjs - typescript 如何在对象中键入自定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64937837/

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