Typescript相同的派生类型,但所有可选键

gas*_*ard 4 typescript

是否可以自动派生此接口:

interface OverrideParamType {
  foo?: FooType
  bar?: BarType
}
Run Code Online (Sandbox Code Playgroud)

从这一个

interface ParamType {
  foo: FooType
  bar: BarType
}
Run Code Online (Sandbox Code Playgroud)

用途是以以下结尾的函数:

return Object.assign ( {}, baseParams, overrideParams )
Run Code Online (Sandbox Code Playgroud)

Nit*_*mer 9

从打字稿2.1你可以做到:

interface ParamType {
    foo: FooType
    bar: BarType
}

type PartialParamType = Partial<ParamType>;
Run Code Online (Sandbox Code Playgroud)

定义Partial是:

type Partial<T> = {
    [P in keyof T]?: T[P];
};
Run Code Online (Sandbox Code Playgroud)

更多相关内容:映射类型

在操场上的一个例子.

请注意,不需要自己定义Partial类型,它是lib.d.ts的一部分.

  • 很棒的功能! (2认同)