티스토리 뷰

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://github.com/typescript-eslint/typescript-eslint/blob/v2.34.0/packages/eslint-plugin/docs/rules/no-non-null-assertion.md )

 

출처 : ( https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html )

댓글