将接口扩展为 TypeScript 中不需要的接口
Extend an interface as not Required in TypeScript
使用Partial
实用程序类型扩展不需要的接口,例如
interface SpecificLocation extends Partial<Location> {}
。实用程序类型构造一个新类型,其中提供的Partial
类型的所有属性都设置为可选。
索引.ts
interface Location { address: string; } interface SpecificLocation extends Partial<Location> { x: number; y: number; } const example: SpecificLocation = { x: 5, y: 10, };
Partial实用程序类型允许我们将
特定类型的所有属性设置为可选。
我们在扩展它时将Location
接口传递给Partial
实用程序类型,因此我们不需要address
在使用该
SpecificLocation
类型时设置属性。
如果在扩展的时候只需要将接口的部分属性设置为optional,可以:
索引.ts
interface Location { address: string; country: string; } interface SpecificLocation extends Omit<Location, 'address'>, Partial<Pick<Location, 'address'>> { x: number; y: number; } const example: SpecificLocation = { country: 'Chile', x: 5, y: 10, };
这个例子看起来有点恶心,但不难推理。
我们做的第一件事是基于接口创建一个新接口Location
,为此address
省略了属性。
我们使用Pick
实用程序类型address
从接口中获取属性的类型,并使用实用程序类型将Location
其设置为可选Partial
。
在
SpecificLocation
界面中,该country
属性是必需的,但该address
属性设置为可选。如果您必须对多个属性执行此操作,则|
在将它们传递给实用程序类型时应使用管道将它们分开。
索引.ts
interface Location { address: string; country: string; city: string; } interface SpecificLocation extends Omit<Location, 'address' | 'city'>, Partial<Pick<Location, 'address' | 'city'>> { x: number; y: number; } const example: SpecificLocation = { country: 'Chile', x: 5, y: 10, };
在上面的示例中,我们在扩展接口时将address
和city
属性设置为可选,但该country
属性仍设置为必需。
这种方法比在多个接口之间复制相同的属性要好得多,因为我们仍然向代码的读者发出信号,表明两个接口之间存在连接。
如果我们只是复制属性并将它们设置为不需要,我们将失去接口之间的连接。