typescript 打字稿扩展不需要的接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29650402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:59:19  来源:igfitidea点击:

typescript extend an interface as not required

javascriptinterfacetypescript

提问by engincancan

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?

我想将 ISuccessResponse 接口扩展为不需要;我可以覆盖它,但还有其他选择吗?

interface IAppVersion {
    OSVersionStatus: number;
    LatestVersion: string;
    Success?: boolean;
    Message?: string;
}

I don't want to do this.

我不想这样做。

回答by Brad

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

有点晚了,但是 Typescript 2.1 引入了Partial<T>允许您要求的类型:

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

回答by Fenton

If you want Successand Messageto be optional, you can do that:

如果你想要Success并且Message是可选的,你可以这样做:

interface IAppVersion {
    OSVersionStatus: number;
    LatestVersion: string;
    Success?: boolean;
    Message?: string;
}

You can'tuse the extendskeyword to bring in the ISuccessResponseinterface, but then change the contract defined in that interface (that interface says that they are required).

不能使用extends关键字引入ISuccessResponse接口,然后更改该接口中定义的协定(该接口表示它们是必需的)。

回答by Chris Edwards

As of TypeScript 3.5, you could use Omit:

从 TypeScript 3.5 开始,您可以使用Omit

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

回答by blorkfish

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