简体   繁体   English

输入打字稿

[英]Typing in Typescript

I have function with a parameter named param like this: 我有一个名为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
}

Can I use for same parameter , two different interfaces? 我可以使用相同的参数,两个不同的接口吗? Thank you! 谢谢!

You can, and you have the parameter syntax correct! 您可以,并且您的参数语法正确! For reference, TypeScript refers to this as a union type . 作为参考,TypeScript将其称为联合类型

The main caveat to using them is that you can only access the common members across all the types - for example, both your interfaces contain name , value and id , so you would be able to use these in your function. 使用它们的主要警告是,您只能访问所有类型的公共成员 - 例如,您的接口都包含namevalueid ,因此您可以在函数中使用它们。 However, only interfaceTwo has the selected member, so that wouldn't be available. 但是,只有interfaceTwo具有selected成员,因此无法使用。

As an aside, I don't know if the example is something you just typed up on the fly, so you may well already know this, but your interfaces are not defined correctly - you need to use the interface keyword and end the lines with semicolons. 顺便说一句,我不知道这个例子是你刚刚输入的东西,所以你可能已经知道这一点,但你的接口没有正确定义 - 你需要使用interface关键字并结束行分号。 It's also a convention to give types TitleCase names: 给类型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