如何概括除某些对象属性外的所有对象属性?

How to generalize all object properties except some?

我希望所有属性都具有特定类型,但我希望显式声明的属性覆盖它:

interface Potato {
  a: number
  [all:string]: string
}

您可以使用 intersection types:

来实现
type PotatoAll = { [all: string]: string };
type Potato = PotatoAll & { a: number };

let p = {} as Potato;

p['foo'] = 'foo';
p.a = 1;
p['a'] = 1;

p['foo'] = 1; //error
p['a'] = 'a'; //error
p.a = 'a'; //error