on
[TypeScript] Non-null assertion operator, rxjs 설치 명령어
[TypeScript] Non-null assertion operator, rxjs 설치 명령어
728x90
angular 강의를 듣던 중 그대로 따라쳤는데 오류가 났다.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable, ObservedValueOf } from 'rxjs'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-developer', templateUrl: './developer.component.html', styleUrls: ['./developer.component.scss'] }) export class DeveloperComponent implements OnInit { name = new Observable(); //강의에서는 Observable객체로 선언해주지 않았는데 그랬더니 오류가 났다. constructor(private route:ActivatedRoute) { //this.name=this.route.snapshot.paramMap.get('name')!; // ^ non-null expression 이렇게 쓴다. null이 아니라고 약속해주는 것 this.name = this.route.params.map(p => p.name); // 이 패키지를 쓰려면 import만으로는 불가능하고 rxjs를 따로 설치해줘야 한다. } ngOnInit(): void { } }
1. new Observable() 객체라고 지정 생성해주지 않자 에러를 뿜었다. route.params.map에서 리턴값이 observable이길래 해당 객체로 생성해주니 에러가 사라졌다. (Property 'map' does not exist on type 'Observable')
2. 동기적으로 name을 주입받는 경우 바로 주입받으니 에러가 났다. null인지 string인지 확인할 수 없다는 에러 문구가 떴다. (Typescript: Type 'string | undefined' is not assignable to type 'string')
3. import 'rxjs/add/operator/map'; 로 해결 안 될 때 rxjs 설치 명령어: npm install --save rxjs-compat
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 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 }
from http://jazzodevlab.tistory.com/66 by ccl(A) rewrite - 2021-05-13 11:26:22