토막지식시리즈/javascript 토막지식
[Typescript] Non-null assertion operator (Non-null 단언 연산자)
GrapeMilk
2021. 6. 28. 14:13
Goal
- Non-null assertion operator란?
Non-null assertion operator란?
접미에 붙는 느낌표(!) 연산자인 단언 연산자는 해당 피연산자가 null, undeifned가 아니라고 단언해준다.
해당 피연산자가 null, undefined가 아닌 타입의 value를 갖는다고 프로그래머가 단언할 때 에러등을 방지하기 위해 사용한다.
// 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
but eslint에서는 Non-null assertion이 the strict null-checking mode의 이점을 이용하지 않는다며 사용을 권장하지 않고 있다.
interface Foo {
bar?: string;
}
const foo: Foo = getFoo();
const includesBaz: boolean = foo.bar!.includes('baz'); // 올바르지 않은 예시
const includesBaz: boolean = foo.bar && foo.bar.includes('baz'); // 올바른 예시
출처 : ( https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html )