typescript extend an interface as not required
23,180
Solution 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
Solution 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).
Solution 3
As of TypeScript 3.5, you could use Omit
:
interface IAppVersion extends Omit<ISuccessResponse, 'Success' | 'Message'> {
OSVersionStatus: number;
LatestVersion: string;
Success?: boolean;
Message?: string;
}
Solution 4
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
-
engincancan about 4 years
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.