gpt4 book ai didi

javascript - 键入对象时出现问题 Typescript 错误 - 无索引签名

转载 作者:行者123 更新时间:2023-11-29 23:09:48 25 4
gpt4 key购买 nike

我有一个对象需要输入,但不确定如何输入。以下是我看到的错误,我的代码在下面。

Element implicitly has an 'any' type because type '{ LIV: string; MAN: string; LDN: string; }' has no index signature. [7017]

type Props = {
city: string;
cityMap: {
LIV: string;
MAN: string;
LDN: string;
};
};

const Cities = ({ city }: Props) => {
const cityMap = {
LIV: 'Liverpool',
MAN: 'Manchester',
LDN: 'London'
};

const city = cityMap[city];
return <>{city}</>;
};

最佳答案

使用 noImplictAny typescript 不会让您索引到具有任意字符串的对象(因为这不是真正的类型安全,并且此类索引操作的结果将隐式为 any )

有几种可能的解决方案。

city 的类型更改为 keyof Props['currencyMap']

type Props = {
city: keyof Props['currencyMap'];
currencyMap: {
LIV: string;
MAN: string;
LDN: string;
};
};

const Cities = ({ city }: Props) => {
const cityMap = {
LIV: 'Liverpool',
MAN: 'Manchester',
LDN: 'London'
};

const cityName = cityMap[city];
};.

或者使用类型断言告诉编译器你确定 city 将是一个合适的键:

const Cities = ({ city }: Props) => {
const cityMap = {
LIV: 'Liverpool',
MAN: 'Manchester',
LDN: 'London'
};

const cityName = cityMap[city as keyof Props['currencyMap']];
};

或者您可以使用检查来确保 city 是具有自定义类型保护的预期键:

const Cities = ({ city }: Props) => {
const cityMap = {
LIV: 'Liverpool',
MAN: 'Manchester',
LDN: 'London'
};
const isCity = (c: string): c is keyof Props['currencyMap'] => c in cityMap;
if (isCity(city)) {
cityMap[city];
}else { /* What now ? error ? */ }
};

关于javascript - 键入对象时出现问题 Typescript 错误 - 无索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54019830/

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