반응형
SMALL
Type System
타입 시스템
- 컴파일러에게 사용하는 타입을 명시적으로 지정.
- 컴파일러가 자동으로 타입을 추정
타입 스크립트의 Type System
- 타입을 명시적으로 지정할 수 있음.
- 타입을 명시적으로 지정하지 않으면 컴파일러가 자동으로 타입을 추론(타입 추론)
타입이 하는 일
// n의 타입을 지정하지 않았으므로 any로 추론됨.
// 리턴 타입은 number로 추론(NaN도 Number)
function func1(n) {
return n * 10;
}
console.log(func1(5)) //50
console.log(func1('Hello') + 1); // NaN
이런 문제를 해결하기 위해 nonImplicitAny 옵션을 사용하여 TS가 추론 중 'any'라고 판단하면, 에러를 발생시켜 명시적 지정을 유도할 수 있습니다.
// 리턴 타입이 number로 추론.
function func1(n: number) {
if (a > 0) {
return n * 2;
}
}
console.log(func1(2)); // 4
// undefined + 2 가 실행됨.
console.log(func1(-2) + 2); // NaN
strictNullChecks 옵션을 켜면 모든 타입에 자동으로 포함된 'null', 'undefined' 를 제거합니다.
// 명시적으로 지정하지 않은 함수의 리턴 타입이 number | undfined 로 추론.
function func1(n: number) {
if (a > 0) {
return n * 2;
}
}
console.log(func1(2));
console.log(func1(-2) + 2); // error : Object is possibly 'undefined'.
noImplicitReturns 옵션을 사용하면 함수 내 모든 코드가 값을 리턴하지 않으면, 에러를 발생.
function func1(n: number) {
if (a > 0) {
return n * 2;
}
}
// error : Not all code paths return a value.
타입을 만드는 방법
interface HumanInterface {
name: string,
age: number;
}
type HumanTypeAlias = {
name: string;
age: number;
}
function func2(a: HumanInterface): string {
return `이름이 ${a.name} 이고, 나이는 ${Math.floor(a.age / 10) * 10} 입니다.`;
}
console.log(func2('Hello')); // error: Argument of type 'string' is not
//assignable to parameter of type 'PersonInterface'.
Structural Type System vs nominal Type System
structural type system
- 구조가 같으면 같은 타입.
interface IHuman {
name: string;
age: number;
speak(): string;
}
type HumanType = {
name: string;
age: number;
speak(): string;
};
let humanInterface: IHuman = {} as any;
let humanType: HumanType = {} as any;
humanInterface = humanType;
humanType = humanInterface;
nominal type system
- 이름이 다르면 구조가 같더라도 다른 타입.
- C. Java 가 대표적이다.
반응형
'프론트개발 > TypeScript' 카테고리의 다른 글
[TypeScript] 인터페이스(Interface) (0) | 2022.07.19 |
---|---|
[TypeScript] 타입 호환성과 별칭 (0) | 2022.07.18 |
[TypeScript] 타입 스크립트의 타입(2) (0) | 2022.07.16 |
[TypeScript] 타입 스크립트의 타입(1) (0) | 2022.07.16 |
[TS vs JS] 타입스크립트와 자바스크립트 (0) | 2022.07.15 |
댓글