TypeScript 개념 - 2
* 출처 : https://github.com/ZeroCho/ts-all-in-one
GitHub - ZeroCho/ts-all-in-one
Contribute to ZeroCho/ts-all-in-one development by creating an account on GitHub.
github.com
* void 타입
- 타입은 return값을 사용하지 안 겠다는 뜻(메서드나 매개변수에서는 리턴값 사용 가능, but 조심해야 함)
- 결과값을 반환하지 않는 함수에 설정, 반면 결과 값을 반환하는 함수의 경우 명시적으로 반환 값에 타입 기술 가능
출처 : https://yamoo9.gitbook.io/typescript/types/function-union-void
function / union / void 타입 - TypeScript Guidebook
오류 메시지에서 말한 any 타입이 아닌, number, string 타입으로만 인자를 전달 받으려면 매개변수에 다음과 같이 설정해 사용합니다.
yamoo9.gitbook.io
// 리턴 값 타입이 명시적으로 설정되지 않는 함수
function assignClass(name:string): void {
document.documentElement.classList.add(name);
}
// 리턴 값 타입이 숫자인 함수
function factorial(n:number): number {
if (n < 0) { return 0; }
if (n === 1) { return 1; }
return n * factorial(n-1);
}
// 리턴 값 타입이 문자인 경우
function repeat(text:string, count:number=1): string {
let result:string = '';
while(count--) { result += text; }
return result;
}
* 타입만 선언하고 싶을 때는 declare 사용
- 구현은 다른 파일에 있어야 함
declare const a: string;
declare function a(x: number): number;
declare class A {}
* 타입 가드(Type Guard)
- 타입 가드 사용 시 조건문에서 객체의 타입을 좁혀갈 수 있음
- typeof와 instanceof 사용 시 해당 조건문 블록 내에서는 해당 변수의 타입이 다르다는 것(=좁혀진 범위의 타입) 이해함
function numberOrNumArray(a: number | number[]) {
if(Array.isArray(a)) { //a = number로 인식
a.concat(4);
} else {
a.toFixed(3)
}
}
numberOrNumArray(123)
numberOrNumArray([1,2,3])
function numOrStr(a: number | string) {
if (typeof a === 'string') { //문자열일 경우
a.split(',');
} else { //숫자일 경우
a.toFixed(1);
}
}
class A6 {
aaa() {}
}
class B6 {
bbb() {}
}
function aOrB(param: A6 | B6) {
if(param instanceof A6) {
param.aaa();
}
}
aOrB(new A6())
aOrB(new B6())
* 참고 : https://radlohead.gitbook.io/typescript-deep-dive/type-system/typeguard
타입 가드 - TypeScript Deep Dive
TypeScript는 JavaScript의 instanceof, typeof 연산자를 이해할 수 있습니다. 즉 조건문에 typeof와 instanceof를 사용하면, TypeScript는 해당 조건문 블록 내에서는 해당 변수의 타입이 다르다는 것(=좁혀진 범위
radlohead.gitbook.io