문자, 숫자, 불린 타입
let str: string = "Hello World!";
let num: number = 123;
let boo: boolean = true;
객체 타입
const obj: { a: number } = { a: 0 };
obj.a = 123;
배열 타입
const arr1: number[] = [];
const arr2: Array<number> = [];
arr1[0] = 123;
arr2[0] = 123;
arr1.push(456);
arr2.push(456);
함수 타입
const hello1: (msg: string, b: number) => string = (msg, num) => {
return msg;
};
const hello2 = (msg: string, num: number): string => {
return msg;
};
function hello3(msg: string, xyz: number): string {
return msg;
}
Enum 타입
const week = ["Sun", "Mon", "Tue", "wed", "Thu", "Fri", "Sat"];
console.log(week[0]);
console.log(week[6]);
console.log(week.findIndex((d) => d === "Sun"));
console.log(week.findIndex((d) => d === "Sat"));
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
}
console.log(Week[0]);
console.log(Week[6]);
console.log(Week.Sun);
console.log(Week.Sat);
enum Colors {
Red,
Green = 4,
Blue,
}
console.log(Colors.Red);
console.log(Colors[0]);
console.log(Colors.Green);
console.log(Colors.Blue);
console.log(Colors[4]);
enum Colors2 {
Red = "r",
Green = 4,
Blue,
}
console.log(Colors.Red);
console.log(Colors.r);
Void 타입
const hello: (msg: string) => void = (msg) => {
console.log(`Hello ${msg}`);
};
const hi: (msg: string) => undefined = (msg) => {
return undefined;
};
hello("World");
Tuple 타입
const arr: number[] = [4, 5];
arr[2] = 6;
arr[3] = 7;
const tup: [number, number] = [4, 5];
tup[2] = 7;
tup.push(6);
tup.splice(2, 0, 6);
const userA: [number, string, boolean] = [1, "Heropy", true];
const userB: [number, string, boolean] = ["Neo", 2, false];
const userC: [number, string, boolean] = [3, "Evan", true, "abc@gmail.com"];
Never 타입
const nev: [] = [];
nev.push(6);
const myError: (m: string) => never = (msg) => {
throw `에러! - ${msg}`;
};
try {
myError("Never 타입...");
} catch (err) {
console.log(err);
}
Any 타입
let anything: any = "Hello";
anything = 123;
anything = { a: "A" };
anything = [1, 2, 3];
const a: string = anything;
const b: number = anything;
const c: boolean = anything;
Unknown 타입
let anything2: unknown = "Hello";
anything2 = 123;
anything2 = { a: "A" };
anything2 = [1, 2, 3];
const d: string = anything2;
const e: number = anything2;
const f: boolean = anything2;
if (typeof anything2 === "string") {
const g: string = anything2;
}
let any: any = "hello";
console.log(any.toUpperCase());
any = 123;
console.log(any.toUpperCase());
let unk: unknown = "hello";
console.log(unk.toUpperCase());
if (typeof unk === "string") {
console.log(unk.toUpperCase());
}
unk = 123;
if (typeof unk === "number") {
console.log(unk.toUpperCase());
}
Union 타입
let uni: string | number | number[];
uni = "Hello";
uni = 123;
uni = [1, 2, 3];
Intersection 타입
type UserA = {
name: string;
age: number;
};
type UserB = {
isValid: boolean;
};
const user1: UserA = {
name: "A",
age: 12,
isValid: true,
};
const user2: UserB = {
name: "B",
age: 85,
isValid: false,
};
const user3: UserA & UserB = {
name: "C",
age: 40,
isValid: false,
email: "abc@gmail.com"
};