Borislav Hadzhiev
Thu Feb 24 2022·2 min read
Photo by Robson Morgan
Use a union type to solve the "Type 'null' is not assignable to type" error in
TypeScript, e.g. name: string | null
. The type of the specific value has to
accept null
, because if it doesn't and you have strictNullChecks
enabled in
tsconfig.json
, the type checker throws the error.
Here are 2 examples of how the error occurs.
// 👇️ Function return value set to object function getObj(): Record<string, string> { if (Math.random() > 0.5) { // ⛔️ Error Type 'null' is not assignable to type // 'Record<string, string>'.ts(2322) return null; } return { name: 'Tom' }; } interface Person { name: string; // 👈️ name property set to string } const obj: Person = { name: 'Tom' }; // ⛔️ Type 'null' is not assignable // to type 'string'.ts(2322) obj.name = null;
The function in the first example returns a null
value or an object, but we
haven't specified that the function might return null
.
The object in the second example has a type of string
for the name
property,
but we are trying to set the property to null
and get the error.
You can use a union type to solve the error.
// 👇️ using union function getObj(): Record<string, string> | null { if (Math.random() > 0.5) { return null; } return { name: 'Tom' }; } interface Person { // 👇 using union name: string | null; } const obj: Person = { name: 'Tom' }; obj.name = null;
We used a union type to set the return value of the function to either an object
with string keys and values or null
.
This approach allows us to return an object or a null
value from the function.
In the second example we set the name
property in the object to have a type of
string
or null
Now we are able to set the property to a value of null
without getting the
error.
If you have to access the name
property, e.g. to call the toLowerCase()
method on it, you have to use a type guard, because the property is possibly
null
.
interface Person { // 👇 using union name: string | null; } const obj: Person = { name: 'Tom' }; // ⛔️ Error: Object is possibly 'null'.ts(2531) obj.name.toLowerCase();
You can get around this with a simple type guard.
interface Person { // 👇 using union name: string | null; } const obj: Person = { name: 'Tom' }; if (obj.name !== null) { // ✅ Now obj.name is string console.log(obj.name.toLowerCase()); }
The "Type 'null' is not assignable to type" error can be suppressed by setting
strictNullChecks
to false
in your tsconfig.json
file.
{ "compilerOptions": { "strictNullChecks": false, // ... 👇️ rest } }
When strictNullChecks
is set to false
, null
and undefined
are ignored by
the language.
This is not advisable as it can lead to unexpected errors at runtime.
When you set strictNullChecks
to true
, null
and undefined
have their own
types and you get errors when using them when a value of different type is
expected.