anaotation
변수를 선언할 때, 타입을 지정하는 방식
원시값
const stringSample: string = "string"; //변수뒤에 콜론과 타입을 넣는다
const numberSample: number = 1;
const booleanSample: boolean = true;
const nullSample: null = null;
const undefinedSample: undefined = undefined;
배열
const strArr: string[] = []; //대괄호 앞의 타입은 배열요소의 타입이다
strArr.push("hello");
strArr.push("world");
const numArr: number[][] = [];
numArr.push([1],[2],[3]);
//[[1], [2], [3]]
튜플
const arr: [string, number] = ['kim' 28]; //초기값을 필수로 넣어야 한다
const arrTwp : [string, number] = []; //Error
객체
const user: {
id: number;
email: string;
password: string;
} = {
id: 1,
email: "kim1@gamil.com",
password:"kim1"
}
//지정한 프로퍼티의 타입은 같은 이름의 프로퍼티와 매핑된다
//지정한 프로퍼티 순서대로 초기화하지 않아도 된다
함수
const introduce = (name: string, age: number): void => {
console.log(`hello, i'm ${name}, ${age} years old.`);
}
//매개변수에 각각 타입을 지정하고, 함수의 반환 값을 지정한다
//함수가 반환할 값이 없다면 반환값 타입을 void로 지정한다
//반환값을 void로 지정한 함수가 값을 반환하면, 그 값은 void가 되어 사용할 수 없다
메서드
const user: {
name: string;
age: number;
greeting: (name: string, age: number)=> void
} = {
name: "kim",
age: 35,
greeting: (name: string, age: number): void => {
console.log(`i'm ${name}, ${age} years old.`)
}
type별칭
type을 정의하는 키워드
type User = {
id: number,
email: string,
password: string
}
const user: User = {
id: 1,
email: "kim1@gmail.com",
password: "kim1"
}
1. type별칭의 첫글자는 대문자로 작성하는게 관례이다
2. 생성한 type은 annotation 형식으로 사용한다
interface
다른 interface와 상속할수 있는 키워드
interface User {
id: number;
email: string;
password: string;
}
const user = {
id: 1,
email: "kim1@gmail.com",
password: "kim1"
}
interface UserDetail extends User {
name: string;
age: number
}
const userDetail = {
id: 2,
email: "kim2@gmail.com",
password: "kim2",
name: "kim",
age: 25
}
1. interface는 extends로 다른 interface를 상속받아 확장할 수 있다
2. 생성한 interface는 annotation 형식으로 사용한다
Union
OR기능을 추가한 문법
type Count = string | number;
const countBook = (count: Count): void => {
console.log(`i have ${count} books`);
}
countBook("four");
countBook(4);
1. 여러 타입일 수 있는 값은 OR 연산자를 사용하여 타입을 지정한다
intersection
2개 이상의 타입을 조합한 타입
interface User {
id: number;
emai: string;
password: string;
}
type Admin = User & {
adminName: string;
}
const user: User = {
id: 1,
email: "user1@gamil.com",
password: "user1"
}
const admin: Admin = {
id: 2,
email: "admin1@gamil.com",
password: "admin1",
adminName: "John"
}
1. intersection은 2개 이상의 타입을 type별칭으로 정의한다
2. interface으로는 intersection을 정의할 수 없고, 오직 type별칭으로만 정의해야 한다
generic
타입을 변수화 시킬 수 있는 문법
const func = <T>(a: T, b: T): T[] => {
return [a, b];
}
func<number>(4, 2);
func<string>("hello", "world!");
1. generic은 사용 시점에 타입을 지정한다
interface Profile<T> {
name: string;
department: T;
}
const employee1: Profile<"developer"> = {
name: "kim",
department: "developer"
}
const employee2: Profile<{ department: "planning", category: "book" }> = {
name: "Lee",
department: {
department: "planning",
category: "book"
}
}
1. interface와 generic은 자주 같이 사용된다