Thursday, April 15, 2021

TypeScript Question Mark and Exclamation Mark

Here is how to use in combination to determine if property is null or undefined.

interface Product {
    id: number,
    name?: any 
}

let product: Product = {id: 5, name: "some str"};

if(product!.name) console.log("ok")

product = {id: 5}
if(product!.name) console.log("not printed")

product = {id: 5, name: null}
if(product!.name) console.log("not printed")

Second if will not be excecated 'cause property name is not defined. Third if will not be execute 'cause property name is null.