简体   繁体   中英

Typing in Typescript

I have function with a parameter named param like this:

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 .

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. However, only interfaceTwo has the selected member, so that wouldn't be available.

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. It's also a convention to give types TitleCase names:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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