繁体   English   中英

输入打字稿

[英]Typing in Typescript

我有一个名为param的参数的函数,如下所示:

function x(param: One | Two) {
    //do something
}

interface One {
    value: IValue,
    name: string,
    id: number
}
interface Two {
    value: IValue2,
    name: string,
    id: number,
    selected: boolean
}

我可以使用相同的参数,两个不同的接口吗? 谢谢!

您可以,并且您的参数语法正确! 作为参考,TypeScript将其称为联合类型

使用它们的主要警告是,您只能访问所有类型的公共成员 - 例如,您的接口都包含namevalueid ,因此您可以在函数中使用它们。 但是,只有interfaceTwo具有selected成员,因此无法使用。

顺便说一句,我不知道这个例子是你刚刚输入的东西,所以你可能已经知道这一点,但你的接口没有正确定义 - 你需要使用interface关键字并结束行分号。 给类型TitleCase名称也是一种约定:

function x(param: InterfaceOne | InterfaceTwo){
    console.log(param.name);     // Valid!
    console.log(param.id);       // Valid!

    console.log(param.value);    // Valid - but has the type IValue | IValue2,
                                 // so you can only access the common fields
                                 // of those types!

    console.log(param.selected); // INVALID - InterfaceOne doesn't have a selected member
}

interface InterfaceOne {
    value: IValue;
    name: string;
    id: number;
}

interface InterfaceTwo {
    value: IValue2;
    name: string;
    id: number;
    selected: boolean;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM