npm install typescript
# typescript μ€ν
npx tsc
# error -> νμ€ κ΅¬μ± νμΌμ νλ‘μ νΈ ν΄λμ μΆκ°ν΄μ νμ€μκ² μ»΄νμΌν νμΌμ μλ €μ€μΌ ν¨
npx tsc [μ»΄νμΌν νμΌλͺ
]
# React + TS νμ μμ±
npx create-react-app [νλ‘μ νΈλͺ
] --template typescript
π [μ°Έκ³ μλ£] Adding TypeScript | Create React App
// typeμ μλ¬Έμλ‘ μ§μ !
// [μ«μν]
let age: number;
age = 12;
let ages: number = 12;
// [λ¬Έμν]
let userName: string;
userName = 'Max';
// [Boolean]
let isInstructor: boolean;
isInstructor = true;
// [Array]
let hobbies: string[]; // λ¬Έμν λ°°μ΄
hobbies = ['Sprots', 'Cooking'];
// [Object]
let person: {
name: string;
age: number
};
person = {
name: 'Max',
age: 20
}
// κ°μ²΄λ₯Ό μ¬λ¬ κ° κ°μ§ λ°°μ΄
let people: {
name: string;
age: number
}[];
// [Type inference(νμ
μΆλ‘ )]
// λ¬Έμμ΄ νμ
μ μΆλ‘ νμ¬ λ€λ₯Έ νμ
μ΄ μ€λ©΄ error
// -> κ°κΈμ :stringμ κ°μ΄ νμ
μ§μ μνκ³ νμ
μΆλ‘ μ¬μ©νλκ² μ’μ~
let str = 'Happy Halloween!';
// str = 123; <- error
// [Union Type]: νμ
μ μμ 1κ° μ΄μμ νμ
μ¬μ© κ°λ₯
let str1: string | number = 'Happy Halloween!';
str1 = 123;
// [Type Aliases] -> μ½λ κ°κ²°, κ΄λ¦¬ easy
// λ°λ³΅ν΄μ μ¬μ© κ°λ₯
type Person = {
name: string;
age: number;
}
let person1: Person;
let people1: Person[];
// [Functions & types]
// λ§€κ° λ³μ νμ
λΏλ§ μλλΌ λ°ν νμ
λ μκ°ν΄μΌ νλ·
function add(a: number, b: number): number {
return a + b;
}
function printOutput(value: any) {
console.log(value)
}
// returnλ¬Έμ΄ μμ΄μ typeμ΄ voidλ‘ νμ
μΆλ‘ λ¨
// void: null, undefinedμ λΉμ·νμ§λ§ νμ ν¨μμ κ²°ν©ν΄μ μ¬μ©!
// [Generics] => μ μ°μ±, νμ
μμ μ± μΈ‘λ©΄μμ κ΅³~
// κΈ°μ‘΄ λ°°μ΄μ λ³κ²½νμ§ μκ³ μλ‘μ΄ κ° μΆκ° κ°λ₯
function insertAtBeginning<T>(array: T[], value: T) {
const newArray = [value, ...array];
return newArray;
}
// ν¨μ 맀κ°λ³μλ€μ any typeμΌλ‘ μ§μ ν΄μ€μ μ΄λ₯Ό κ°μ§κ³ λ§λ€μ΄μ§ λ°°μ΄ λ΄μ κ°μ νμ€λ‘ νμ
μ κ²μ¬ν μ μμ
// μ¦, μ΄νμ νμ€μ κΈ°λ₯μ μμ΄λ²λ¦° μ
,,
// Solution: μ λ€λ¦ νμ
μ€μ ν΄μ£ΌκΈ°!! ex. <T>
// => μ λ€λ¦ νμ
μ μ¬μ©νμ¬ νμ€μκ² any typeμ΄ μλλ κ²μ μλ €μ€¬κΈ° λλ¬Έμ μ΄νμ λ°°μ΄ λ΄μ μ«μ νμ
μΈμ§ λ±μ νμ
κ²μ¬κ° κ°λ₯ν΄μ§!
const demoArray = [1, 2, 3];
const updatedArray = insertAtBeginning(demoArray, -1); // [-1, 1, 2, 3]
// updatedArray[0].split(''); <- error
// why error? updatedArray[0]λ μ«μνμ
μ΄λκ±Έ μΆλ‘ ν΄λκ³ , split() λ©μλλ μ«μμ μ¬μ© λΆκ°νλ―λ‘
// μλ λ caseλ κ°μ μ½λ
// let numbers: number[] = [1, 2, 3];
// let numbers: Array<number> = [1, 2, 3];