Home > Enterprise >  Typescript variable with type and undefined
Typescript variable with type and undefined

Time:11-24

interface Data {
   name: string,
   address: string
}

interface Detail {
   detail: Data | undefined
}

export const Profile: Detail {

   profile: undefined

}

Here I have initially defined profile as undefined. It works fine. I can update prifle with Data type.

What I want to achieve here is at some point I should be able to update profile with undefined.

I can initialize with undefined but I can not update it with undefined.

How can I make it to take either Data type or undefined

CodePudding user response:

You are missing an = sign, the last three lines should be

export const Profile: Detail = {
    profile: undefined
}

CodePudding user response:

The Botly Noob is right, also you have to modify the param name, otherwise it won't be able to be assigned to the type Detail, Object literal may only specify known properties, and 'profile' does not exist in type 'Detail'

CodePudding user response:

Are you looking for something like:

interface Data {
   name: string;
   address: string;
}

export const Profile = {
   profile: Data | undefined;
}

I couldn't really understand the usecase of Detail interface.

CodePudding user response:

Try null instead of undefined.

  • Related