将打字稿界面限制为另一个界面

时间:2019-01-23 16:15:56

标签: typescript

提供打字稿界面:

interface alpha {
  name?: string;
  age?: string;
  sign?: string;
}

我想创建另一个接口,该接口仅限于来自另一个接口的有限属性集

interface beta {
  age?: string;
}

这可能吗?

如果有人要:

interface beta {
  foo?: string;
}

我希望它无效。

1 个答案:

答案 0 :(得分:2)

很好的答案:How to remove fields from a TypeScript interface via extension

因此,您创建了一个名为“帮助程序类型”的Omit可以从界面中忽略某些属性:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

同样,您也可以修改现有接口的属性,这可以多次使用:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
}
type Partial<T> = {
    [P in keyof T]?: T[P];
}

此外,有时更容易将其改正。从beta扩展alpha。

interface alpha extends beta {
  name?: string;
  sign?: string;
}

interface beta {
  age?: string;
}

const x: alpha = {
    name: "foo" // valid
}

const y: beta = {
    name: "where" // invalid
}