简体   繁体   中英

How can I prevent from filling this object with a undefined?

This happens when level starts with the value undefined.

This code works fine in JavaScript but when I am using TypeScript it doesn't work.

interface Find {
    level?: string;
}

let find: Find = {};

if (!!level) {
     find.level = level;
}

Final value of find:

{"level":"undefined"}

Instead of just:

{}

You have the value:

{"level":"undefined"}

If it was undefined you would see:

{"level":undefined}

What you actually have is the string "undefined" .

Fix

interface Find {
    level?: string;
}

let find: Find = {};

if (!!level && level !== "undefined") {
     find.level = level;
}

And now you will get {} .

More

TypeScript does not change JavaScript runtime behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM