问题
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