接口属性依赖于其他属性

i47*_*898 1 typescript

假设我有下一个界面:

interface TestInterface {
  id?: string;
  type?: string;
}
Run Code Online (Sandbox Code Playgroud)

是否有可能以一种方式重写,当我执行检查id !== undefined 时,它会自动意味着type属性也已定义?

Nen*_*nad 6

您可以使用联合类型来模仿这一点。

简单的例子:

interface INonNullable {
    id: string;
    type: string;
}
interface INullable {
    id?: undefined;
    type?: undefined;
}
type FinalType = INonNullable | INullable;

function testId(x: FinalType) 
{
  if (x.id !== undefined) {
    x.type // string
  }
}
Run Code Online (Sandbox Code Playgroud)

FinalType是可选的,您可以简单地(x: INonNullable | INullable)在任何地方使用。

添加类型保护功能:

您还可以使用类型保护功能来测试您的标准并以这种方式缩小类型:

interface INonNullable {
    id: string;
    type: string;
}
interface INullable {
    id?: undefined;
    type?: undefined;
}
type FinalType = INonNullable | INullable;

function isNonNullable(x: FinalType): x is INonNullable
{
  return x.id !== undefined;
}

let x = {};

if (isNonNullable(x)) {
  x.type // string;
}
Run Code Online (Sandbox Code Playgroud)

您在 Typescript 文档中有更多关于此的信息: 用户定义的类型保护

可重复使用Empty<T>

另一个巧妙的选择,如帕特里克罗伯茨在评论中提到的,使用映射类型和泛型制作更可重用的解决方案:

interface INonNullable {
    id: string;
    type: string;
}
interface INullable {
    id?: undefined;
    type?: undefined;
}
type FinalType = INonNullable | INullable;

function isNonNullable(x: FinalType): x is INonNullable
{
  return x.id !== undefined;
}

let x = {};

if (isNonNullable(x)) {
  x.type // string;
}
Run Code Online (Sandbox Code Playgroud)