Andreea Tirgovatu
Andreea Tirgovatu

Reputation: 111

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!

Upvotes: 4

Views: 59

Answers (1)

Joe Clay
Joe Clay

Reputation: 35807

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

Upvotes: 4

Related Questions