#How do I convince TypeScript that yes, a value is initialised, actually.

14 messages · Page 1 of 1 (latest)

daring roost
#

I have some javascript code that essentially boils down to something like

let apple: number;
let banana;
eval("apple = 1;");
banana = apple;

Which gives an error like Variable 'apple' is used before being assigned.ts(2454)

Is there a magic incantation I can use to convince typescript that apple is actually assigned? Maybe a chain of as's or something?

dusk wyvern
#
let apple: number;
let banana;
eval("apple = 1;");
banana = apple!; // notice the !
daring roost
#

Great, thanks! I can't believe that didn't show up in my google searches

fading wigeonBOT
#
let apple!: number;
let banana;
eval("apple = 1;");
banana = apple;
clever totem
#

this is the more common solution

#

also works for class fields

#

the issue with the operator form is that it only tells TS it's initialized in that one specific place

daring roost
#

Cool. Is that syntax in the docs somewhere?

daring roost
#

Nice, good find! I was having trouble with it too. Maybe it needs a pull request to add it to the docs proper?

#

Or an issue