4

I am migrating some JS code to TS and I'm faced with an issue of differentiating between a null type in TypeScript versus just giving a null value of a field in an object.

Here is a dummy example:

export const performProcedure = () => {
    let newPerson = {
        name: null,
        birthdate: null
    }

    if (<someCheck>) {
        newPerson.name = "Default name";
    }

    ...
}

As far as JS is concerned, the above code works. However, when I incorporate TS, I get an error saying that Type 'Default name' is not assignable to type 'null'. It seems to be doing this because now TS interprets name : null to be saying that name is of type null which is not what I want. I just want to initialize it to null.

How do I get around my issue?

2 Answers 2

4

Typescript resolved that the newPerson.name has type of "null" since you put null there. The best way to get arround it is to be as specific as possible. If you want to allow null value and string, create an interface that says so:

interace Person {
    name: string | null;
    birthdate: Date | null;
}

let newPerson: Person = { ... }

This is most explicit. Probably better way is to use undefined instead of null. Then you can use just optional parameter:

interace Person {
    name?: string;
    birthdate?: Date;
}

It's worth noting that if you enable all of the strict checks in your tsconfig, you cannot pass null to a property defined as string. And that is a good thing, you don't want to see any "Cannot read property 'length' of null" erro message.

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

2 Comments

Is it really necessary to construct an interface for this? In my function, I am just trying to return the newPerson object with the appropriate values set. Sometimes the birthdate field will be string and other times, it can be null. Is this possible at all? My tsconfig.json has strictNullChecks turned on.
Well it is not necessary but it would help. I would probably extract this piece of code to a method like getPerson() and this method would need a return type. Which would be the Person interface. Or you can use the conditional (ternary) operator and write: name: <someCheck> ? "Default name" : null. This time the Typescript will resolve the type as string | null.
2

You can tell typescript that name should be a string.

let newPerson = {
    name: <string>null,
    birthdate: null
}

It would be even better to have a Person interface.

interace Person {
    name: string;
    birthdate: Date;
}
let newPerson: Person = { 
    name: null, 
    birthdate: null 
};

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.