基于可选泛型的接口中的强制键

Mandatory key in interface based on optional generic

Typescript 中是否有一种方法可以在将泛型传递给接口时使接口具有强制键?

我正在寻找一种方法,以便仅当将泛型传递给接口时才能够为接口中的键定义类型。

例如

interface IExample {
  foo: string
}
​
/* You can't declare 2 interfaces of the same name, but this shows the structure I am aiming for */
interface IExample<T> {
  foo: string,
  bar: T
}
​
/* Allowed */
const withoutBar: IExample {
  foo: 'some string'
}
​
/* Not allowed, as I've passed in a generic for Bar */
const withoutBar: IExample<number> {
  foo: 'some string'
}
​
/* Allowed */
const withBar: IExample<number> {
  foo: 'some string',
  bar: 1
};
​
/* Not allowed as I have not passed in a generic for Bar */
const withBar: IExample {
  foo: 'some string',
  bar: 1 // Should error on "bar" as I have not passed in a generic
};

您可以使用条件类型作为类型别名。

type IExample<T = void> = T extends void ?  {
  foo: string
} : {
  foo: string,
  bar: T
}
​​
/* Allowed */
const withoutBar: IExample = {
  foo: 'some string'
}
​
/* Not allowed, as I've passed in a generic for Bar */
const withoutBar: IExample<number> = {
  foo: 'some string'
}
​
/* Allowed */
const withBar: IExample<number> = {
  foo: 'some string',
  bar: 1
};
​
/* Not allowed as I have not passed in a generic for Bar */
const withBar: IExample = {
  foo: 'some string',
  bar: 1 // Should error on "bar" as I have not passed in a generic
};

Playground