打字稿:找不到索引索引意味着什么?

时间:2019-07-12 23:29:26

标签: typescript

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从界面更改为type时。错误消失了。

type IHuman = {
    name: string;
}

什么是错误,为什么在第二种情况下消失了。有没有更好的方法来键入Instance。我希望Instance是可以接受任何对象的常规类型。有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

我相信这是因为TypeScript中的interface无法像其他更通用的接口一样被鸭子式输入。您可以IHuman扩展Instance以使其起作用,但是您可能不想为要在其上运行checkRequiredProps的每个接口都这样做。

编辑:从下面的注释中,checkRequiredProps的功能签名被更改为具有string s且可以为any类型的键的对象。这仍将允许输入数组,但是字符串,布尔值,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,以确保狼人享有与人类相同的权利。

答案 1 :(得分:0)

[531-660j, 267-801j,...]
相关问题