Home > Net >  Can't access a property of a variable of multiple types
Can't access a property of a variable of multiple types

Time:12-31

I have created a type that can be of some other type or some interface, so I can use that in a function.

type Value = string | number
interface IUser { name: string, id: string }
export type IGlobalUser = Value | IUser;

Now, when I want a function to get a parameter of type IGlobalUser, i would expect to be able to access props of the interface IUser. Like this:

foo(user: IrGlobalUser) { alert(user.name) } 

However, TypeScript says:

Property 'name' does not exist on type 'string | number | IUser'.   
Property 'name' does not exist on type 'string'.

I want the function to be able to accept both Value and IUser and to use it, any ideas how to achieve it?

CodePudding user response:

The function accepts both Value and IUser. TypeScript is warning you that you cannot know if the type of user is string or number or IUser and in the first two cases user does not have the property name.

Use a enter image description here

  • the second type is IUser as expected

    enter image description here

  • When compiled to JavaScript, the isUser function and if statement will obviously be there. But you probably want a check like that somewhere in your code anyway. Writing it using a Type Guard will do the necessary check at runtime, but will also make TypeScript aware of the two different scenarios and give you feedback accordingly.

    CodePudding user response:

    JS solution => better for runtime also

    foo(user: IrGlobalUser) {
      alert((typeof user === 'object') && user.name)
    } 
    

    TS solution => Work only at compile time

    foo(user: IrGlobalUser) {
      alert((user as IUser).name)
    } 
    
    • Related