typescript extend an interface as not required

拥有回忆 提交于 2019-12-10 00:50:03

问题


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; 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.


回答1:


A bit late, but Typescript 2.1 introduced the Partial<T> type which would allow what you're asking for:

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



回答2:


If you want Success and Message to be optional, you can do that:

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).




回答3:


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;
}


来源:https://stackoverflow.com/questions/29650402/typescript-extend-an-interface-as-not-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!