TypeScript/ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ TypeScript

[ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ] ! Non-null assertion operator

Rainbow๐ŸŒˆCoder 2022. 5. 2. 15:31
728x90
!: ์ด๋ž€?

๋А๋‚Œํ‘œ๋ฅผ ์ง€์šฐ๊ณ  ๋‚˜์˜ค๋Š” ์—๋Ÿฌ : 'ui'์€(๋Š”) ์ด๋‹ˆ์…œ๋ผ์ด์ €๊ฐ€ ์—†๊ณ  ์ƒ์„ฑ์ž์— ํ• ๋‹น๋˜์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.ts(2564)
ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๊ฐ€ ํ˜น์‹œ null์ผ์ง€๋„ ๋ชจ๋ฅด๋Š” ๋Œ€์ƒ์— ์ปดํŒŒ์ผ์—๋Ÿฌ๋ผ์ธ ๋„์›Œ์ฃผ๋Š”๋ฐ
ํ”„๋กœ๊ทธ๋ž˜๋จธ๊ฐ€ null์ด ์•„๋‹ˆ๋ผ๊ณ  ํ™•์‹ ์ด ์žˆ์„๋•Œ์—
TSC Null์ฒดํฌ์— ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ํ•ด์ฃผ๋Š” ๊ฒƒ
 

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. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}

 

null์ด ์•„๋‹Œ ์–ด์„ค์…˜ ์—ฐ์‚ฐ์ž

์ƒˆ๋กœ์šด !ํ›„์œ„ ํ‘œํ˜„์‹ ์—ฐ์‚ฐ์ž๋Š” ์œ ํ˜• ๊ฒ€์‚ฌ๊ธฐ๊ฐ€ ํ•ด๋‹น ์‚ฌ์‹ค์„ ๊ฒฐ๋ก ์ง€์„ ์ˆ˜ ์—†๋Š” ์ปจํ…์ŠคํŠธ์—์„œ ํ”ผ์—ฐ์‚ฐ์ž๊ฐ€ null์ด ์•„๋‹ˆ๊ณ  ์ •์˜๋˜์ง€ ์•Š์Œ์„ ์ฃผ์žฅํ•˜๋Š” ๋ฐ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŠนํžˆ ์ด ์ž‘์—… ์€ with ๋ฐ ์ œ์™ธ x!์œ ํ˜•์˜ ๊ฐ’์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค . ํ˜•์‹ ๋ฐ ์˜ ํ˜•์‹ ์–ด์„ค์…˜๊ณผ ์œ ์‚ฌํ•˜๊ฒŒ null ์ด ์•„๋‹Œ ์–ด์„ค์…˜ ์—ฐ์‚ฐ์ž๋Š” ๋‚ด๋ณด๋‚ด์ง„ JavaScript ์ฝ”๋“œ์—์„œ ๊ฐ„๋‹จํžˆ ์ œ๊ฑฐ๋ฉ๋‹ˆ๋‹ค.xnullundefined<T>xx as T!

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}

 

728x90