๐ด Why not JavaScript

// ์ด์ํด!!
[1, 2, 3, 4] + false
// '1, 2, 3, 4false'
// ์ด์ํด!!
function divide(a, b) {
return a / b;
}
divide("xxxxx");
// NaN => ์ Error๋ฅผ ์ถ๋ ฅํ์ง ์์ง?
๐ Implicit Types vs Explicit Types

let a = "hello"
let b : boolean = false // But, TypeScript๊ฐ ์ถ๋ก ํ๋๋ก ํ๋๊ฒ ๋ซ๋ค.
๐ก Types of TS part One

type Name = string;
type Age = number;
type Player = {
name: Name,
age?: Age // ์ ํ์ ํ์
}
const player1 : Player = {
name: "player1"
}
const player2 : Player = {
name: "player2",
age: 28
}
// using normal function
function playerMaker(name: string) : Player {
return {
name
}
}
// using arrow funciton
const playerMaker = (name: string) : Player => ({ name });
const player3 = playerMaker("player3");
player3.age = 28
๐ข Types of TS part Two
โช readonly

type Name = string;
type Age = number;
type Player = {
readonly name: Name,
age?: Age
}
const playerMaker = (name: string) : Player => ({ name })
const ryong = playerMaker("ryong");
ryong.name = "jeong"; // Error!

const numbers: readonly number[] = [1, 2, 3, 4];
numbers.push(1); // Error
โช tuple

// Tuple :: ํญ์ ์ ํด์ง ๊ฐฏ์์ ์์๋ฅผ ๊ฐ์ ธ์ผ ํ๋ array๋ฅผ ์ง์
const player: [string, number, boolean] = ["ryong", 28, true];
player[0] = 1; // ERROR

const player: readonly [string, number, boolean] = ["ryong", 28, true];
player[0] = "hi"; // ERROR
โช any

// any :: TypeScript ๋ณดํธ์ฅ์น๋ก๋ถํฐ ๋น ์ ธ๋์ค๊ธฐ
const a : any[] = [1, 2, 3, 4]
const b : any = true
a + b // Not Error
๐ต Types of TS part Three
โช unknown

// API๋ก๋ถํฐ ์๋ต์ ๋ฐ๋๋ฐ ์ด๋ค ํ์
์ธ์ง ๋ชจ๋ฅผ ๋๋ unknown๋ฅผ ์ฌ์ฉ
let a: unknown;
let b = a + 1; // ERROR
if (typeof a === 'number') {
// ์ฝ๋์์ a์ ํ์
์ด number์ธ์ง ํ์ธํ๊ธฐ ๋๋ฌธ
let b = a + 1;
}
let c = a.toUpperCase(); // ERROR
if (typeof a === 'string') {
let b = a.toUpperCase();
}
โช void

// void :: ์๋ฌด๊ฒ๋ return ํ์ง ์๋ ํจ์๋ฅผ ๋์
function hello() {
console.log('x');
}
const a = hello();
a.toUpperCase(); // ERROR because of 'void'
โช never

// never :: ํจ์๊ฐ ์ ๋ return ํ์ง ์์ ๋ ๋ฐ์
// ์๋ฅผ ๋ค์ด ํจ์์์ exception์ด ๋ฐ์ํ ๋
function hello(): never {
// return 'X'; // ERROR
throw new Error("X");
}
function hello(name: string|number) {
if (typeof name === 'string') {
name // name: string
} else if (typeof name === 'number') {
name // name: number
} else {
name // name: never
}
}
'TypeScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ TS ] Classes and Interfaces (0) | 2022.07.17 |
---|---|
[ TS ] Functions (0) | 2022.07.17 |