let helloWorld = "Hello World"; //string
interface User {
name: string;
id: number;
}
const user: User = {
name: "Hayes",
id: 0,
};
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserAccount("Murphy", 1);
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;
function wrapInArray(obj: string | string[]) {
if (typeof obj === "string") {
return [obj];
} else {
return obj;
}
}
type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;
interface Backpack<T> {
add: (obj: T) => void;
get: () => T;
}
declare const backpack: Backpack<string>;
const object = backpack.get(); //object -> string
backpack.add(23); //type warning
interface Point {
x: number;
y: number;
}
function printPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
// 타입을 지정하지 않아도 Point 타입과 형식이 일치하기 때문에 타입 검사 통과
const point = { x: 12, y: 26 };
printPoint(point);
//하위집합인 x, y만 지정되어 있으면 ok
const point3 = { x: 12, y: 26, z: 89 };
printPoint(point3); // prints "12, 26"
const rect = { x: 33, y: 3, width: 30, height: 80 };
printPoint(rect); // prints "33, 3"
//error
const color = { hex: "#187ABF" };
printPoint(color);
// 객체와 클래스 간에 형태를 따르는 방법에는 차이가 없음
class VirtualPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const newVPoint = new VirtualPoint(13, 56);
printPoint(newVPoint); // prints "13, 56"
출처:
https://www.typescriptlang.org/ko/docs/handbook/typescript-in-5-minutes.html