0

I am using react with typescript 3.7.2: I have three components: "Menu Component", "Login User" and "Logged in".

In the "Menu Component" I have a "user" property, this property can be defined or null:

interface Props {
    user: UserIF | null;
}

The "Menu Component" checks if the "user" property is defined. If it is not defined (null) then menu redirects to the component "Login User" otherwise it redirects to the "Logged in" component.

Now I would like to define the typescript definition in the components as follows:

"Login user":

interface Props {
    user: UserIF | null;
}

"Logged in"

interface Props {
    user: UserIF;
}

Typescript is now complaining that user can also be Null in the "Logged in" component. But Typescript doesn't know that the variable user can't be null in the "Logged in" component.

How can I tell typescript that I have only a defined user varaible in the "Logged in" component?

3
  • What is UserIF? Is it an object? Commented Nov 26, 2019 at 13:01
  • This is the definition of user variable. export interface UserIF { firstName: string; lastName: string; } Commented Nov 26, 2019 at 13:05
  • If you have declared a default value (an empty object) for user (in a reducer or so), you can just use partial user: Partial<UserIf>; Commented Nov 26, 2019 at 13:06

1 Answer 1

1

You need to have two separated interfaces:

interface NotLoggedProps {
    user: null;
}

interface LoggedProps {
    user: UserIF;
}

type MenuProps = NotLoggedProps | LoggedProps; // at Menu level user can be logged or not

And use them accordingly in different components.

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

2 Comments

What if the user content is dynamic and comes from async http request? You can't dynamically change two interfaces...
You cannot never change interface in dynamic way. Every generic type is transformed into final type. Generic types are only for code reuse. Also async call is runtime, types not exists at this point.

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.