简体   繁体   中英

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

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:

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

As of TypeScript 3.5, you could use 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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