0
type User ={
    id: number;
    name?: string;
    nickname?: string;
}

type Info = {
    id: number;
    city?: string;
}

type SuperUser = User & Info;

let su:SuperUser;
su.id = 1; 

console.log(su);

This is a simple code. I did try the intersection types.Why console return me 'su' is undefined?

5
  • Where do you think you set a value for su? let su: SuperUser; only sets a type, the value is undefined. Commented Apr 19, 2020 at 9:24
  • @johnsharpe : sorry I did not pay attention to the type keyword. Comment deleted Commented Apr 19, 2020 at 9:26
  • @jonrsharpe I do su.id = 1; Commented Apr 19, 2020 at 9:48
  • And that's what's triggering the TypeError. Commented Apr 19, 2020 at 9:51
  • @jonrsharpe can u give me the solution? please. Commented Apr 19, 2020 at 9:56

1 Answer 1

1

You need to assign some values to your variable first otherwise it would be undefined like this:

type User ={
    id: number;
    name?: string;
    nickname?: string;
}

type Info = {
    id: number;
    city?: string;
}

type SuperUser = User & Info;

let su:SuperUser = { // <-- First we assign some value
    id: 1
};
su.id = 2; // <-- and then we can use or change the value

console.log(su);

try on the playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.