Static Types (set during development) vs Dynamic Types (resolved at runtime)
// JavaScript는
// 런타임 상에서 자료형을 체크를 해야하지만
function add(n1, n2) {
if(typeof n1 !== 'number' || typeof n2 !== 'number') {
throw new Error('Incorrect input');
}
return n1 + n2;
}
// TypeScript는
// 타입 어노테이션을 통해 지정을 해준다
function add(n1: number, n2: number) {
return n1 + n2;
}
👉 TypeScript의 핵심 Primitive types은 모두 소문자
let fullName: string = 'Jinju Baek';
let age: number = 26;
let sentence: string = `Hi, this is ${ fullName }
I'll be ${ age + 1 } years old next year.`;
console.log(Symbol('foo') === Symbol('foo')); // false
👉 주로 접근 제어시 쓰는 경우가 많다
const sym = Symbol();
const obj = {
[sym]: "val"
};
console.log(obj[sym]) // "val"
// 이 변수들에 할당할 수 있는 것들은 거의 없다
let u: undefined = undefined;
let n: null = null;
let u: undefined = null; // (X)
let v: void = undefined; // (O)
let union: string | null | undefined = 'Jinju';
let n: null = null;
console.log(n); // null
console.log(typeof n); // object
let u: undefined = undefined;
console.log(u); // undefined
console.log(typeof u); // undefined
// Created by object literal
const person = {name: 'Jinju', age: 26};
// person is not "object" type
// person is "{name: 'Jinju', age: 26}" type
// Created by Object.create(오브젝트 or null)
const dog = Object.create({name: 'ddoa', age: 2});
let obj: object = {};
obj = {name: 'Jinju'};
obj = [{name: 'Jinju'}];
obj = 26; // Error
obj = true; // Error
declare function create(o: object | null): void;
create({ prop: 0 });
create(null);
create(32); // Error
create("string"); // Error
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
let list: (number | string)[] = [1, 2, 3, "4"];
let x: [string, number];
x = ["Jinju", 26]; // 순서와 타입이 일치해야 함
x = [32, "someone"]; // Error
const person: [string, number] = ["Jinju", 26];
const [first, second] = person; // destructuring (분해할당)
// person의 요소를 가지고 나와서 [] 안에 넣음
function returnAny(msg): any {
console.log(msg);
};
const any1 = returnAny('아무거나 리턴');
any1.toString(); // 타입에러 뜨지 않음 > any이기 때문
let looselyTyped: any = {};
let d = looselyTyped.a.b.c.d;
// ^ = let d: any
function leakingAny(obj: any) {
const a: number = obj.num; // number로 지정해주면 누수를 막을 수 있음
const b = a + 1;
return b;
}
const c = leakingAny({ num : 0 });
c.indexOf('0');
declare const maybe: unknown;
const aNum: number = maybe;
if(maybe === true) { // typeguard
const aBoolean: boolean = maybe; // (O)
const aString: string = maybe; // (X)
}
if(typeof maybe === 'str') { // typeof typeguard
const aStr: string = maybe; // (O)
const aBoolean: boolean = maybe; // (X)
}
function error(msg: string): never {
throw new Error(msg);
}
function fail() {
return error('failed');
}
function infiniteLoop(): never {
while(true) {}
}
let a: string = 'hello';
if(typeof a !== 'string') {
let b: never = a;
}
type Indexable<T> = T extends string ? T & { [index: string]: any } : never;
const b: Indexable<{}> = '';
function returnVoid(msg: string): void {
console.log(msg);
return undefined;
}