Reputation: 432
I am new to Typescript. Stuck in a terminal error.Type 'string | null' is not assignable to type 'string'
const myModel = {
name: values.name || null ,
};
and the function where a string const Field = "myplace";
is set initially and it should be string.
const MyFunction = () => {
const Field = "myplace";
... ... rest code here
it is working as expected; showing terminal error. How to remove the terminal error? Do I make mistake in defining type error? Thanks.
Upvotes: 5
Views: 19919
Reputation: 1838
The reason TypeScript is complaining is this line. If either values, place or name are undefined, null or false, then name will be null. If name can be null, you cannot use it in a function that expects a string, because null is not a string.
...
-> name: values?.place?.name || null
}
You need to make sure that the name property is always a string, even if the input value isn't a string, by giving it a default value that is in fact a string:
-> name: values?.place?.name || "some default string"
Also, you're using a boolean logic operator, but you really should be using a nullish coalescing operator:
const myModel = {
id: values?.place?.id ?? <default id>,
name: values?.place?.name ?? <default name>,
};
The ||
operator returns the left value if it's true, and the right hand value otherwise. So 0 || 5
returns 5
, but 1 || 5
returns 1
. The nullish coalescing operator does sort of the same thing but instead checks if the left hand value is null or undefined: 0 ?? 1
returns 0
, but null ?? 0
returns 0
.
The big difference is with strings:
// s is a string or null
const v = s || "default"
// s is null: v is "default"
// s is undefined: v is "default"
// s is "": v is "default" <--- IMPORTANT! "" is a valid string, but it's "false"
// otherwise: v is s
const v = s ?? "default"
// s is null: v is "default"
// s is undefined: v is "default"
// otherwise: v is s
Combined with optional chaining, this becomes quite powerful:
// If either a, b, c or d are null or undefined, v is undefined
const v = a?.b?.c?.d;
// If either a, b, c or d are null or undefined, v is "hello"
const v = a?.b?.c?.d ?? "hello";
Upvotes: 7