example)
// 문자열
const str: string = 'hello';
// 숫자
const num: number = 10;
// 배열
const arr: Array<string> = ["heeje", "hi"]; /// <= 꺽쇠 안에는 타입이 들어간다.
arr.push('hi');
// 배열 - 리터럴 적용
const items: string[] = []; // <= 리터럴을 쓰고 앞에 타입을 붙여주면 된다.
// items.push(10);
// 튜플 => 특정 인덱스의 타입을 지정해준다.
const address: [string, number] = ['판교', 40];
// 객체
const obj: object = {};
// obj.a = 10;
// 타입 객체
const person: { age: number; name: string } = { age: 100, name: 'Capt' };
person.age = 101;
// 진위값
let isLogin: boolean = false;
함수의 선언 예시
// 타입스크립트 함수 선언 - 함수의 반환 타입
function add(a: number, b: number): number {
return a + b;
}
//or
//with arrow function
const sum = (a: number, b: number): number => {
return a + b;
};
함수에서의 옵셔널
// 두 번째 파라미터는 옵셔널로 있어도 되고 없어도 된다.
function printText(text: string, type?: string) {
console.log(text);
}
printText("hi");
타입의 별칭
type Todo = { id: number; title: string; done: boolean };
let todoItems: Todo[];
// api
function fetchTodoItems(): Todo[] {
const todos = [
{ id: 1, title: "안녕", done: false },
{ id: 2, title: "타입", done: false },
{ id: 3, title: "스크립트", done: false },
];
return todos;
}
Interface => 코드의 간결화
interface Todo {
id: number;
title: string;
done: boolean;
}
let todoItems: Todo[];
// api
function fetchTodoItems(): Todo[] {
const todos = [
{ id: 1, title: "안녕", done: false },
{ id: 2, title: "타입", done: false },
{ id: 3, title: "스크립트", done: false },
];
return todos;
}