타입 단언
// 단언 키워드 - as
// Non-null 단언 연산자 = !
// 잘못 사용하면 any처럼 typescript 사용 이유가 없어질 수도 있다.
// 1
const el = document.querySelector('body') as HTMLBodyElement // null이 아니고 HTMLBodyElement일 것임을 단언해줌
el.textContent = 'Hello World!'
const el2 = document.querySelector('body')
el2!.textContent = 'Hello World!' // 또는 non-null 연산자를 이용할 수 있다.
const el3 = document.querySelector('.title');
if (el3) {
el3.textContent = 'Hello World!'
} // type guard
// 2
function getNumber(x: number|null|undefined) {
if (x) {
return Number(x.toFixed(2))
}
// return Number((x as number).toFixed(2))
// return Number(x!.toFixed(2)) non-null 연산자 사용
// x는 null일 수도 있고 undefined일 수도 있어서 에러발생. 타입 단언을 어떻게 해줄것인가?
// null이 들어오면 어떻게 될까
// 단언이 잘못되었을 때, 코드상에서 에러가 발생하지는 않는다. 동작시킬 때까지는 알 수 없다
}
function getValue(x:string | number, isNumber:boolean) {
if (isNumber) {
return Number((x as number).toFixed(2)); // toFixed는 문자열을 반환한다.
}
return (x as string).toUpperCase();
}
getValue('hello world', false) // 'HELLO WORLD'
getValue(3.1415926535, true) // 3.14
할당 단언
let num2!:number // ! - 할당단언, 값을 할당하지 않았지만 값이 있다고 알려주는 연산자
// non-null과는 다르게 사용됨. 콜론 기호 앞에 사용
console.log(num2) // 할당하기 전에 사용해서 에러가 남
'TYPESCRIPT' 카테고리의 다른 글
[Typescript] 인터페이스 (interface) (0) | 2023.12.04 |
---|---|
[Typescript] 타입 가드(type guard) (0) | 2023.12.04 |
[Typescript] 타입 추론 (type inference) (1) | 2023.12.04 |
[Typescript] 타입 종류 (0) | 2023.12.04 |
[TypeScript] 타입스크립트 (0) | 2023.04.28 |
타입 단언
// 단언 키워드 - as
// Non-null 단언 연산자 = !
// 잘못 사용하면 any처럼 typescript 사용 이유가 없어질 수도 있다.
// 1
const el = document.querySelector('body') as HTMLBodyElement // null이 아니고 HTMLBodyElement일 것임을 단언해줌
el.textContent = 'Hello World!'
const el2 = document.querySelector('body')
el2!.textContent = 'Hello World!' // 또는 non-null 연산자를 이용할 수 있다.
const el3 = document.querySelector('.title');
if (el3) {
el3.textContent = 'Hello World!'
} // type guard
// 2
function getNumber(x: number|null|undefined) {
if (x) {
return Number(x.toFixed(2))
}
// return Number((x as number).toFixed(2))
// return Number(x!.toFixed(2)) non-null 연산자 사용
// x는 null일 수도 있고 undefined일 수도 있어서 에러발생. 타입 단언을 어떻게 해줄것인가?
// null이 들어오면 어떻게 될까
// 단언이 잘못되었을 때, 코드상에서 에러가 발생하지는 않는다. 동작시킬 때까지는 알 수 없다
}
function getValue(x:string | number, isNumber:boolean) {
if (isNumber) {
return Number((x as number).toFixed(2)); // toFixed는 문자열을 반환한다.
}
return (x as string).toUpperCase();
}
getValue('hello world', false) // 'HELLO WORLD'
getValue(3.1415926535, true) // 3.14
할당 단언
let num2!:number // ! - 할당단언, 값을 할당하지 않았지만 값이 있다고 알려주는 연산자
// non-null과는 다르게 사용됨. 콜론 기호 앞에 사용
console.log(num2) // 할당하기 전에 사용해서 에러가 남
'TYPESCRIPT' 카테고리의 다른 글
[Typescript] 인터페이스 (interface) (0) | 2023.12.04 |
---|---|
[Typescript] 타입 가드(type guard) (0) | 2023.12.04 |
[Typescript] 타입 추론 (type inference) (1) | 2023.12.04 |
[Typescript] 타입 종류 (0) | 2023.12.04 |
[TypeScript] 타입스크립트 (0) | 2023.04.28 |