HolgerJeromin
HolgerJeromin

Reputation: 2462

Easy way to add an additional type to a variable

I have a simple typescript code:

let foo = document.createElement('div');
foo.id='foo';
foo=null;

TS complains correctly that the cleanup line is not valid because foo should be only a div.

let foo: null | HTMLDivElement = document.createElement('div');
foo.id='foo';
foo=null;

Would be ok. But this is really cumbersome. Is there a nice solution like my non working example?

let foo: & null = document.createElement('div');
foo.id='foo';
foo=null;

Upvotes: 0

Views: 45

Answers (2)

paroxyzm
paroxyzm

Reputation: 1499

Your example is contrived - I presume, so I will assume you really need to assign null to some variable to clean it:

Maybe this code would be better for "cleaning"?

let foo = document.createElement('div');
foo.id='foo';
(foo as any) = null;

Upvotes: 0

Benoit
Benoit

Reputation: 791

It really depends if you have the strict (or strictNullChecks) flag enabled in your tsconfig.json file or not. If you do have this flag, then you must add the | null part to the type of foo. If you don't have this flag, TypeScript shouldn't complain.

That being said, I would recommend using the strict mode, it really helps avoiding runtime errors due to null or undefined references. I don't know how the rest of your code looks, but IMO you shouldn't have to "clear" the reference by assigning null to it, nowadays garbage collection is strong enough to handle the "free unused memory" step.

Upvotes: 1

Related Questions