1. ํจ์ ์์ฑ
const add = (num1: number, num2: number):void => {
console.log(num1 + num2)
}
2. ์ ํ์ ๋งค๊ฐ๋ณ์
const hello = (name?: string) => {
return `Hello, ${name || 'world'}`
}
hello() // Hello, world
hello('purple') // Hello, purple
3. ๋งค๊ฐ๋ณ์ ์ต์ ๊ฐ
// ์ถ์
๊ฐ์ด ๋ค์ ์๋ ๊ฒฝ์ฐ
const hello = (name: string, age?: number): string => {
if (age !== undefined) {
return `Hello, ${name}. You are ${age}.`;
} else {
return `Hello, ${name}.`;
}
}
hello('Sam',30) // "Hello, Sam. You are 30."
hello('Sam') // "Hello, Sam."
// ์ถ์
๊ฐ์ด ์์ ์๋๊ฒฝ์ฐ
const hello2 = (age: number | undefined, name: string): string => {
if (age !== undefined) {
return `Hello, ${name}. You are ${age}.`;
} else {
return `Hello, ${name}.`;
}
}
hello2(undefined,'Sam') // "Hello, Sam."
4. ๋๋จธ์ง ๋งค๊ฐ๋ณ์
const add = (...nums: number[]) => {
return nums.reduce((acc,cur) => acc + cur, 0)
}
add(1,2,3) // 6
5. This
// 1. interface
interface User {
name: string;
}
// 2. interface๋ก ๊ฐ์ฒด Sam ์์ฑ
const Sam: User = { name:'Sam'}
// 3. ํจ์ ์ค์ (ํ์ดํ ํจ์๋ก ์์ฑํ๋ฉด ์ค๋ฅ๊ฐ ์๊ธด๋ค)
function showName(this:User ,age:number, gender:'m'|'f') {
console.log(this.name, age, gender)
}
const getSame = showName.bind(Sam) // showNameํจ์๊ฐ Sam ๊ฐ์ฒด๋ฅผ ๋ณด์ฌ์ฃผ๋๋ก ํจ
getSame(30,'m') // "Sam", 30, "m"
6. ๋งค๊ฐ๋ณ์ ํ์ ์ ๋ฐ๋ผ ๊ฒฐ๊ณผ๊ฐ ๋ค๋ฅผ ๋
// 1. interface
interface User {
name: string
age: number
}
// 2. ์ค๋ฒ๋ก๋๋ฅผ ์ฌ์ฉํด์ ํ์
์ ๋ฐ๋ฅธ ๊ฒฐ๊ณผ๋ฅผ ๋ค๋ฅผ๊ฒ ์ค์
function join(name: string, age: number): User;
function join(name: string, age: string): string;
function join(name: string, age: number | string): User | string {
if (typeof age === 'number') {
return {
name,
age
}
} else {
return "๋์ด๋ฅผ ์ซ์๋ก ์
๋ ฅํด์ฃผ์ธ์"
}
}
const sam : User = join("Sam", 30)
const jane : string = join("Jane","30")
'๊ฐ๋ฐ ๊ณต๋ถ > Typescript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์ฝ๋ฉ์๋ง] typescript - 6 : ํด๋์ค (0) | 2023.03.29 |
---|---|
[์ฝ๋ฉ์๋ง] typescript - 5 : ๋ฆฌํฐ๋ด, ์ ๋์จ/๊ต์ฐจ ํ์ (0) | 2023.03.24 |
[์ฝ๋ฉ์๋ง] typescript - 3 : ์ธํฐํ์ด์ค (0) | 2023.03.22 |
[์ฝ๋ฉ์๋ง] typescript - 2 : ๊ธฐ๋ณธํ์ (0) | 2023.03.21 |
[์ฝ๋ฉ์๋ง] typescript - 1 : ํ์ ์คํฌ๋ฆฝ์ ์ฐ๋ ์ด์ (0) | 2023.03.21 |