gpt4 book ai didi

javascript - typescript 提示显式类型没有索引签名

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:27 24 4
gpt4 key购买 nike

Typescript 在以下代码中引发错误 “元素隐式具有 'any' 类型,因为类型 'HumansToDogs' 没有索引签名。”

一切对我来说似乎都是明确而直接的,任何人都可以帮忙吗?

type HumanName = 'Jessie' | 'Mark';
type DogName = 'Spot' | 'Buddy';

type HumansToDogs = {
[key in HumanName]: DogName; // Isn't this an index signature?
}

const humansToDogs: HumansToDogs = {
'Jessie': 'Buddy',
'Mark': 'Spot',
};

for (const human in humansToDogs) {
const dog = humansToDogs[human]; // Index signature error here
}

最佳答案

for..of 会将循环变量键入为 string。使用 noImplicitAny,您无法索引到具有任意 string 的类型。最简单的解决方案是使用类型断言:

for (const human  in humansToDogs) {
const dog = humansToDogs[human as HumanName]; // Index signature error here
}

关于javascript - typescript 提示显式类型没有索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918775/

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