41

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
  • Do you mean you want Success and Message to be optional in IAppVersion? Commented Apr 15, 2015 at 13:07

4 Answers 4

91

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
Sign up to request clarification or add additional context in comments.

Comments

10

As of TypeScript 3.5, you could use Omit:

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

Comments

9

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.