๐Ÿ“ Non-null assertion operator | TypeScript

Boriยท2022๋…„ 7์›” 20์ผ
0

์–ด์จŒ๋“  ๊ณต๋ถ€

๋ชฉ๋ก ๋ณด๊ธฐ
5/41

๐Ÿ—’ Non-null assertion operator

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.

  • ! ์—ฐ์‚ฐ์ž(๋‹จ์–ธ ์—ฐ์‚ฐ์ž)๋Š” ํ”ผ์—ฐ์‚ฐ์ž๊ฐ€ null ๋˜๋Š” undefined๊ฐ€ ์•„๋‹˜์„ ๋‹จ์–ธํ•  ๋•Œ ์‚ฌ์šฉ
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
    // e๊ฐ€ null ์ด๊ฑฐ๋‚˜ ์œ ํšจํ•˜์ง€ ์•Š์€ entity์ผ ๊ฒฝ์šฐ ์˜ˆ์™ธ ๋ฐœ์ƒ
}
    
function processEntity(e?: Entity) {
    validateEntity(e);
    // Assert that e is non-null and access name
    // e๋Š” null์ด ์•„๋‹˜์„ ๋‹จ์–ธํ•˜์—ฌ name์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.
    let s = e!.name;    
}
  • TypeScript ESLint์—์„œ๋Š” Non-null assertion์„ ์‚ฌ์šฉํ•˜๋ฉด The strict null-checking mode์˜ ์ด์ ์ด ์—†์–ด์ง€๋ฏ€๋กœ ์‚ฌ์šฉ์„ ๊ถŒ์žฅํ•˜์ง€ ์•Š๋Š”๋‹ค.
interface Foo {
  bar?: string;
}

const foo: Foo = getFoo();
    
// Incorrect code for this rule    
const includesBaz: boolean = foo.bar!.includes('baz');
// Correct code for this rule    
const includesBaz: boolean = foo.bar && foo.bar.includes('baz');

์ฐธ๊ณ 

0๊ฐœ์˜ ๋Œ“๊ธ€