티스토리 뷰
토막지식시리즈/javascript 토막지식
[Typescript] Non-null assertion operator (Non-null 단언 연산자)
GrapeMilk 2021. 6. 28. 14:13Goal
- 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 )
'토막지식시리즈 > javascript 토막지식' 카테고리의 다른 글
Typescript 타입 종류 알아보기! (unknown) (0) | 2021.07.10 |
---|---|
Typescript 타입 종류 알아보기! (any) (0) | 2021.07.10 |
vs code에서 typescript run하기 (0) | 2021.01.10 |
JavaScript는 인터프리트언어? 컴파일언어? (0) | 2020.12.15 |
{}의 의미 (JavaScript, ES6, Object Destructuring) (0) | 2020.12.05 |
댓글
최근에 올라온 글
최근에 달린 댓글
TAG
- 20200622
- chapter7
- 20200425
- 20200420
- 20200504
- 20200424
- 20200512
- 20200428
- 백준
- chapter8
- 20200406
- 20201204
- 20200403
- 20200624
- 20200415
- 20200804
- 20200421
- 20200510
- 20200423
- 20200413
- 20200417
- 20200427
- 20200330
- 20200502
- 생활코딩리눅스
- 20200503
- 20200319
- likelion
- 20200317
- 20200429
- Total
- Today
- Yesterday