首页 > 解决方案 > 单个 TypeScript 索引类型中的多个值类型

问题描述

我想要这样的类型:

interface Foo {
  foo: number;
  bar: boolean;
  [others: string]: string;
}

换句话说,我想foo成为一个数字,bar成为一个布尔值,而其他一切都是一个字符串。

但是,这样做会导致错误:

Property 'foo' of type 'number' is not assignable to 'string' index type 'string'.

我以为我会很聪明,而是这样做:

type Foo = {foo: number} & {bar: boolean} & { [others: string]: string }

但是,这会导致使用错误;例如:

const x: Foo = {
  foo: 123,
  bar: false,
  baz: 'hello world'
};

产量:

Type '{ foo: number; bar: false; baz: string; }' is not assignable to type 'Foo'.
  Type '{ foo: number; bar: false; baz: string; }' is not assignable to type '{ [others: string]: string; }'.
    Property 'foo' is incompatible with index signature.
      Type 'number' is not assignable to type 'string'.

如何在 TypeScript 界面中表达我想要传达的内容?

标签: typescript

解决方案


推荐阅读