如何定义一种不同于其他任何类型的财产类型?

xia*_*yao 5 typescript typescript-typings

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

// Property 'bar' of type '{}' is not assignable to string index type 'string'.
Run Code Online (Sandbox Code Playgroud)

我试图使属性barObject字符串,任何其他属性为字符串,如何在没有 的情况下定义它any

Ali*_*adi 2

bar type此错误与您定义的字典无关[key: string]: string;。请检查这里

但你可以这样解决问题:

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

type MainFooType = Foo & {
   bar: Object;
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接

任务可以是:

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
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1012 次

最近记录:

5 年 前