基于可选泛型的接口中的强制性密钥

时间:2019-07-31 08:39:05

标签: typescript typescript-typings typescript-generics

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
};

1 个答案:

答案 0 :(得分:2)

您可以使用带条件类型的类型别名。

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