简体   繁体   English

打字稿扩展不需要的接口

[英]typescript extend an interface as not required

I have two interfaces;我有两个接口;

interface ISuccessResponse {
    Success: boolean;
    Message: string;
}

and

interface IAppVersion extends ISuccessResponse {
    OSVersionStatus: number;
    LatestVersion: string;
}

I would like to extend ISuccessResponse interface as Not Required;我想将 ISuccessResponse 接口扩展为不需要; I can do it as overwrite it but is there an other option?我可以覆盖它,但还有其他选择吗?

interface IAppVersion {
    OSVersionStatus: number;
    LatestVersion: string;
    Success?: boolean;
    Message?: string;
}

I don't want to do this.我不想这样做。

A bit late, but Typescript 2.1 introduced the Partial<T> type which would allow what you're asking for:有点晚了,但是 Typescript 2.1 引入了Partial<T>类型,它可以满足您的要求:

interface ISuccessResponse {
    Success: boolean;
    Message: string;
}

interface IAppVersion extends Partial<ISuccessResponse> {
    OSVersionStatus: number;
    LatestVersion: string;
}

declare const version: IAppVersion;
version.Message // Type is string | undefined

If you want Success and Message to be optional, you can do that:如果您希望SuccessMessage是可选的,您可以这样做:

interface IAppVersion {
    OSVersionStatus: number;
    LatestVersion: string;
    Success?: boolean;
    Message?: string;
}

You can't use the extends keyword to bring in the ISuccessResponse interface, but then change the contract defined in that interface (that interface says that they are required).不能使用extends关键字引入ISuccessResponse接口,但随后更改该接口中定义的协定(该接口表示它们是必需的)。

As of TypeScript 3.5, you could use Omit :从 TypeScript 3.5 开始,您可以使用Omit

interface IAppVersion extends Omit<ISuccessResponse, 'Success' | 'Message'> {
  OSVersionStatus: number;
  LatestVersion: string;
  Success?: boolean;
  Message?: string;
}

Your base interface can define properties as optional:您的基本接口可以将属性定义为可选:

interface ISuccessResponse {
    Success?: boolean;
    Message?: string;
}
interface IAppVersion extends ISuccessResponse {
    OSVersionStatus: number;
    LatestVersion: string;
}
class MyTestClass implements IAppVersion {
    LatestVersion: string;
    OSVersionStatus: number;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM