Home > Software design >  how to resolve the error ts.(2345) in angular?
how to resolve the error ts.(2345) in angular?

Time:05-24

error -Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.ts(2345) there are 2 error in this code 1st in line no.27 and 2nd in line no.32.

CodePudding user response:

Always share some code with it, its impossible to decode it for you. But the error happens in the following case:

let myVar = null;

// ..

myVar = 'assigned a string';

Solution: define the type for myVar to be:

let myVar: string|null

CodePudding user response:

your typescript error is telling you that you are trying to assign a variable of type string | null to a variable that expects a string instead. ex:

let x : string | null = 'something'

function doSomething(foo: string) {
 ...
}

doSomething(x)

this is a simple example. For example, you can use the typescript guards:

let x : string | null = 'something'

function doSomething(foo: string) {
 ...
}

if(typeof x === 'string') {
 doSomething(x)
}

here you can read about.

or you can type casting like:

let x : string | null = 'something'

function doSomething(foo: string) {
 ...
}


doSomething(<string>x)

Typescript is strinct but will help you to avoid boring erros

Good Coding!

  • Related