Home > Back-end >  Type 'string' is not assignable to type 'number' when i assign two value
Type 'string' is not assignable to type 'number' when i assign two value

Time:10-23

I am new in typescript, and i am trying to write a simple program, but i got this error:

Type 'string' is not assignable to type 'number'.

How can i solve the problem?

file.ts:

let aged = true;
let realAge = 0 ;


if (aged) {
  realAge = '4 years';
}

let dogAge = realAge * 7;

console.log(`${dogAge} years`);

CodePudding user response:

That's TypeScript's type checking in action

let realAge = 0; // here the type of realAge is inferred to number

...later in the code

realAge = '4 years'; // the type is now a string

TypeScript ensures that variables type do not change to values other than the ones set or inferred.

You can create a separate variable to store the 'age caption' like '4 years' which will always be a string and keep the value of realAge as a number.

NOT THE BEST

If however you want to keep your code working as it currently is, you can set the following

let aged: boolean = true;

let realAge: string | number = 0;

This however will give you an undesired value, so maybe it's a bad idea

let dogAge = realAge * 7; // weird string multiplication

CodePudding user response:

The Type Inference mechanism automatically assigns types to variables at the declaration and initial assignment time if the type is not specified.

let x = 3;   //x  is now of 'number" type.
x = 'foo';   //<- type error

This can be avoided by assigning an explicit type during the decleration.

In your case,

let realAge: any = 0
  • Related