gpt4 book ai didi

typescript :找不到索引签名是什么意思?

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

interface Instance {
[param: string]: string;
}

const checkRequiredProps = (instance: Instance, requiredProps: string[]) => {
const props = requiredProps.filter((prop: string) => {
return !instance[prop];
});

console.log(props);
};
interface IHuman {
name: string;
}

class Test {
private readonly _name: string;

constructor(human: IHuman = {} as IHuman) {
checkRequiredProps(human, ['name']);
this._name = human.name;
}

public get name(): string {
return this._name;
}
}

const test = new Test({ name: 'loki' });

enter image description here

我有 2 种类型 Instance,这是一个具有任意键值对的简单对象。还有 IHuman 包含 name 属性。我正在尝试将 IHuman 传递给接受 Instance 的函数。我收到如图所示的错误。

但是当我将 IHuman 从接口(interface)更改为 type 时。错误消失了。

type IHuman = {
name: string;
}

关于什么错误以及为什么在第二种情况下错误消失了。有没有更好的方法来输入 Instance。我希望 Instance 成为可以接受任何对象的通用类型。有更好的方法吗?

最佳答案

我相信这是因为 TypeScript 中的 interface 不能像其他更通用的接口(interface)一样被鸭子类型化。您可以让 IHuman 扩展 Instance 以使其工作,但您可能不想为每个要运行的接口(interface)都这样做 checkRequiredProps上。

编辑:从下面的评论中,checkRequiredProps 的函数签名被更改为一个对象,其键是string,并且可以是任何 类型。这仍将允许数组传入,但不应传入字符串、 bool 值、nullundefined

const checkRequiredProps = (instance: {[key: string]: any}, requiredProps: string[]) => {
const props = requiredProps.filter((prop) => {
return !instance[prop];
});

console.log(props);
};

interface IHuman {
name: string;
}

interface IWerewolf {
name: string;
}

class Test {
private readonly _name: string;

constructor(human: IHuman = {} as IHuman, werewolf: IWerewolf = {} as IWerewolf) {
checkRequiredProps(human, ['name']);
checkRequiredProps(werewolf, ['name']);
this._name = human.name;
}

public get name(): string {
return this._name;
}
}

const test = new Test({ name: 'loki' }, { name: 'wolfington' });

添加了另一个接口(interface),以确保狼人享有与人类相同的权利。

关于 typescript :找不到索引签名是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015018/

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