【问题标题】:Typescript, class type is not assignable to index interface打字稿,类类型不可分配给索引接口
【发布时间】:2021-03-13 22:47:25
【问题描述】:

我有一个具有一些公共属性的类,我想将它传递给一个具有索引接口类型的通用参数的函数,但我收到一个编译器错误,上面写着Argument of type 'Car' is not assignable to parameter of type '{ [k: string]: unknown; }'.

有人可以解释什么是错的,因为我假设所有的类都是对象类型的吗?!!

class Car {

  name: string | undefined;

}

function toStr <T extends { [k: string]: unknown }>(i: T) {
  return i.toString();
}


const jeep = new Car();
jeep.name = 'jeep';

toStr(jeep);

【问题讨论】:

  • Car 没有定义索引签名,但函数参数对其有约束。你能解释一下泛型在这里的意义吗? function toStr(i: object) ...function toStr(i: Record&lt;string, any&gt;) ... 都可以使用
  • 或者接受任何带有 toString 方法的类型(应该是一切) toStr(i: {toString(): string}): string
  • @LindaPaiste 从技术上讲并不是所有的东西都会有toString(例如Object.create(null)),但是打字稿无法捕捉到这个
  • 重点是eslint在使用object类型时会报错。

标签: typescript typescript-typings


【解决方案1】:

只需使用object 代替{ [k: string]: unknown }

class Car {

  name: string | undefined;

}

function toStr <T extends object>(i: T) {
  return i.toString();
}


const jeep = new Car();
jeep.name = 'jeep';

const result = toStr(jeep);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2020-06-29
    • 2019-09-25
    • 1970-01-01
    • 2022-08-14
    • 2016-10-25
    • 2018-02-02
    • 2021-06-17
    相关资源
    最近更新 更多