使用 TypeScript 通用接口

Sha*_*aun 2 typescript

我有几种类型的对象,如文章、部门、个人资料等。我为每个对象定义了一个接口,基本上:

interface IArticle {
    title: string;
    body: string;
}

interface IProfile {
    name: string;
    email: string;
}

interface IDivision {
    name: string;
    leader: IProfile;
}
Run Code Online (Sandbox Code Playgroud)

现在,在某些情况下,我希望能够在formTitle显示表单的页面上使用这些属性时添加属性。我以为我可以做这样的事情:

// Failed
interface IForm<T> {
    formTitle: string;
}

function formDisplay(resource: IForm<IProfile>) { }
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我收到一个错误,指示对象属性(nameemail,在这种情况下)不存在于类型IForm<IProfile>。所以我想这不是泛型的正确使用。来自 Ruby 和 JavaScript,我对整个静态类型仍然是新手。

为了解决这个问题,我一直在为每个对象编写单独的接口,如下所示:

// Not reusable
interface IArticleForm extends IArticle {
    formTitle: string;
}
Run Code Online (Sandbox Code Playgroud)

我能想到的另一种选择是向基本接口添加一个可选属性,然后从那里扩展常规对象接口。

// Does not provide helpful type checking
interface IBase {
    formTitle?: string;
}
interface IArticle extends IBase { }
Run Code Online (Sandbox Code Playgroud)

但是我想formTitle在这些表单页面上被要求这样我就不会忘记设置它。有没有办法以可重用的方式将一组必需的属性应用于多个对象?

Tad*_*ork 5

看起来您正在寻找交叉点类型。这允许您将行为混合在一起。你甚至可以给新创建的类型起别名,给它一个方便的名称来描述它的用法。

对于您的示例,请使用:

interface IProfile {
    name: string;
    email: string;
}
interface IForm {
    formTitle: string;
}
type IProfileForm = IForm & IProfile;

function formDisplay(resource: IProfileForm) { }
Run Code Online (Sandbox Code Playgroud)