Home > Blockchain >  Type 'true' is not assignable to type 'null'
Type 'true' is not assignable to type 'null'

Time:07-09

Typescript throw error about my code:

Type 'true' is not assignable to type 'null'.(2322)

const model = {
  foo: true,
  bar: false,
  baz: null,
};

if (true) {
  model.baz = true; // Type 'true' is not assignable to type 'null'.(2322)
}

stackblitz

I want to initial the baz property later in if statement.

Can I do it without create interface for the model? because model just temporary variable.

CodePudding user response:

use interface to tell compiler what type of model is

interface Model {
   foo: boolean,
   bar: boolean,
   baz: boolean | null,
}
const model: Model = {
  foo: true,
  bar: false,
  baz: null,
};
if (true){
  model.baz = true;
}

CodePudding user response:

First you need to define an interface.

interface MyInterface {
  foo: boolean;
  bar: boolean;
  baz: boolean | null
}

Then:

  const model:MyInterface = {
    foo: true,
    bar: false,
    baz: null
  };

  model.baz = true;

If you don't want to define the interface in another line:

  const model: {
    foo: boolean;
    bar: boolean;
    baz: boolean | null;
  } = {
    foo: true,
    bar: false,
    baz: null,
  };

If you don't want to use @ts-ignore and the like, I think you have no choice but to define an interface.

CodePudding user response:

You need to specify the type ob baz property that can be boolean or null.

https://www.typescriptlang.org/play?#code/C4TwDgpgBAtg9gEwgGygXigbwFBSgMzjgC4oAjI5CAQwDsBuXc6gJ1IrirsbzOoC92lGrSgAfKLQCuyZIwC jbAGM4tAM7BYiFKXhJUGHHkIkowFlIgAaJnzYFqydTbsDS02bcXZsAS3woAAoLKwBKLCZ9FAA6Pn50c0sIBWwgA

  • Related