提供打字稿界面:
interface alpha {
name?: string;
age?: string;
sign?: string;
}
我想创建另一个接口,该接口仅限于来自另一个接口的有限属性集
interface beta {
age?: string;
}
这可能吗?
如果有人要:
interface beta {
foo?: string;
}
我希望它无效。
答案 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
}