TypeScript basics

! operator

1
if (a!.b!.c) { }

compiles to JS:

1
2
if (a.b.c) {
}

? operator

1
let x = foo?.bar.baz();

compiles to JS:

1
let x = foo === null || foo === undefined ? undefined : foo.bar.baz();

And:

1
2
3
if (someObj?.bar) {
// ...
}

is equivalent in JS to:

1
2
3
if (someObj && someObj.someProperty) {
// ...
}

TS:

1
2
3
4
5
6
7
8
9
10
interface Content {
getUrl?: () => string;
url?: string;
}
interface Data {
content?: Content;
}
let data: Data | undefined;
const url: string | undefined = data?.content?.getUrl?.();
const url2: string | undefined = data?.content?.url;