【问题标题】:How to define one property type different from any others? [duplicate]如何定义一种不同于其他的属性类型? [复制]
【发布时间】:2021-08-25 01:51:39
【问题描述】:
interface Foo {
  bar: {};
  [key: string]: string;
}

// Property 'bar' of type '{}' is not assignable to string index type 'string'.

我正在尝试使属性barObject 并且任何其他属性都是字符串,如何在没有any 的情况下定义它?

【问题讨论】:

  • 请参阅this question 及其对围绕此类“默认”或“休息”索引签名问题的回答。从该答案翻译代码会产生this。祝你好运!

标签: typescript typescript-typings


【解决方案1】:

此错误与 bar type 无关,而是与您定义的字典 [key: string]: string; 有关。请查看here

但是你可以这样解决问题:

interface Foo {
   [key: string]: string;
}

type MainFooType = Foo & {
   bar: Object;
}

playground link

分配可以是:

const dictionary: { [key: string]: string } = { other: 'val2' };
let b: MainFooType = Object.assign({ bar: {} }, dictionary);

var f = b["bar"] // empty Object
var f1 = b["other"] // val2

【讨论】:

  • 如果你真的想分配给那个类型的变量,它就行不通了。playgroud link
  • 您的字典分配错误。你必须使用 Object.assign 。见this
  • @xiaoxiyao 我把作业部分放在我的答案中。
猜你喜欢
  • 2022-10-31
  • 2019-09-02
  • 2011-09-09
  • 1970-01-01
  • 2018-11-04
  • 2017-02-08
  • 2014-07-06
  • 1970-01-01
相关资源
最近更新 更多