Types
// union
let userId: string | number | boolean = "abc1"
userId = 123
userId = true
// Object
let user: {
name: string;
age: number;
isAdmin: boolean;
id: string | number;
};
user = {
name: "Elly",
age: 20,
isAdmin: true,
id: "abc"
}
// Array
// let hobbies: Array<string>;
let hobbies: string[]; // number[], boolean[]
hobbies = ["Sports", "Cooking", "Reading"]
Function
- void : return이 없을 때 (반환값이 없는 함수의 타입을 지정)
function add(a:number, b:number): void{
const result = a + b;
}
- 자바스크립트에서는 function도 value로 봄
function calculate(a: number, b: number, calcFn: (a: number, b: number) => number) {
calcFn(a, b);
}
calculate(2, 5, add);
Custom types
// func
type AddFn = (a: number, b: number) => number;
function calculate(a: number, b: number, AddFn => number) {
calcFn(a, b);
}
-----
// basic types
type StringOrNum = string | number;
let userID : StringOrNum = "abc1"
userID = 123
-----
// object
type User = {
name: string;
age: number;
isAdmin: boolean;
id: string | number;
};
let user: User;
Interface
- essentially for creating objects : 객체 타입을 선언할 때 사용
interface Credentials {
password: string;
email: string;
}
let creds: Credentials;
creds= {
password: "abc",
email: "123@email.com"
}
interface vs Custom type
- type : can always use the type keyword (union, primitive ...)
- not extendable, but can use "&" to extend
- interface : more limited to object, class types / can't store a union type
- using when implements interface in the class
- easily extendable : can redefine the interface (add more properties, methods...)
class AuthCredentials implements Credentials {
password: string;
email: string;
userName: string;
}
function login(credentials: Credentials) {}
login(creds)
login(new AuthCredentials());
Merging types
type Admin = {
permissions: string[];
};
type AppUser = {
userName: string;
}
// 1.
type AppAdmin = Admin & AppUser;
// 2.
interface AppAdmin extends Admin, AppUser {}
let admin: AppAdmin;
admin = {
permissions: ["login"],
userName: "Elly"
}
Literal Types
let role : "admin"; // only admin can allocated in role
let role : "admin" | "user" | "editor";
Adding Type Guides
type Role = "admin" | "user" | "editor" // union type
let role = Role;
function performAction(action: string, role: Role) {
if (role === "admin" && typeof action === "string") {
...
}
}
Type Narrowing : 타입 좁히기
- TypeScript가 값의 타입을 더 구체적으로 확인하고 제한하는 것
- 조건문 (if, switch, typeof, instanceof) 등을 통해 타입을 좁힘
function processValue(value: string|number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Generic Types
- we can use it when the type is not defined
- 타입을 유연하게 정의하고, 재사용성을 높이기 위해 사용
- 함수, class, interface에 사용, 특정 타입에 의존하지 않음
type DataStorage<T> = {
storage: T[];
add: (data: T) => void;
}
const textStorage: DataStorage<string> = {
storage: ["a", "b", "c"],
add(data) {
this.storage.push(data);
}
}
const userStorage: DataStorage<User> = {
storage: [],
add(user) {
...
}
}
function merge<T, U>(a: T, b: U) {
return {
...a,
...b,
}
}
const newUser = merge({name: "Elly"}, {age: 20})