TypeScriptμμλ κ°μ²΄λ₯Ό μ€λͺ νλ μ΄λ Έν μ΄μ μ λ§λ€ μ μμΌλ©° λ³μ λλ κ°μ²΄λ₯Ό μ μΈν λ, νμ μ μ μν΄μΌνλ€.
μ μνλ λ°©λ²μ interfaceμ typeμ΄ μ‘΄μ¬
μΌλ°μ μΌλ‘ νμ₯μ±μ΄ μ’μ interface μ¬μ©μ κΆμ₯νλ€.
νμ
μ΄ μ¬ννκ±°λ μ λ λ³κ²½λμ§ μλ κ²½μ°μλ typeμ μ¬μ©νμ¬ κ°μ²΄μ νμ
μ μ μνλ€.
interface IUser {
name: string,
age : number
}
let obj: IUser = { name: 'NAME', age: 29 };
type UserType = {
name: string,
age : number
}
let obj: UserType = { name: 'NAME', age: 29 };
const printName = (name : { first : string, last : string}){
return Name : `${first} ${last}`;
}
printName({firstt : 'Will', last : 'Ferrell'})
let coordinate: {x: number, y: number} = {x : 34, y: 20};
function randomCoordinate(): {x: number, y: number}{
return{ x: Math. };
}
κ°μ²΄ 리ν°λ΄ ννμ λ°ν νμ
μ΄λ
Έν
μ΄μ
μ κ°μ§λ ν¨μλ₯Ό λ§λ€ μ μκ³
κ°μ²΄ νμ
μ μ¬μ©νλ λ³μλ₯Ό κ°μ§ μ μλ€.
ν¨μμλν νλΌλ―Έν° νμ
μ λν
μ΄μ
μ μμ±ν΄ κ°μ²΄κ° λκ² ν μ μλ€.
const printName = (name : { first : string, last : string}){
return Name : `${first} ${last}`;
}
printName({first : 'Will', last : 'Ferrell' , age : 50}); // error
const person = {first : 'Will', last : 'Ferrell' , age : 50}
printName(person); // success μ μλ first, last νλ‘νΌν° μΈμλ 무μνλ€.
νμ μ μ¬μ¬μ©νκ³ μ΄λ¦μ μ μ₯νλ λ°©λ²μ΄λ©° μ΄ νλ‘νΌν°λ₯Ό κ°μ§λ 볡μ‘ν κ°μ²΄ νμ μ μ¬μ©λλ€.
type Point = {
x : number;
y : number;
}
function doublePoint(point: Point): Point {
return { x: point.x*2, y: point.y*2};
}
μ€μ²©λ κ°μ²΄μΈ κ²½μ° μ΄λ
Έν
μ΄μ
μ²λ¦¬λ₯Ό μ΄λ»κ² ν κΉ?
κ°μ νμμΌλ‘ μ€μ²©νμ¬ νμ
μ μ μνλ©΄ λλ€.
type Song = {
title: string;
artist: string;
numStreams: number;
credits: { producer: string; writer: string};
};
const mySong: Song = {
title : "Melody",
artist : "eminem",
numStreams : 123,
credits: {
producer : "Paul",
writer : "Alex"
}
}
κ°μ²΄μ κ°μ²΄ νμ
μ€μ μ κ΄ν κ² μ€ μ νμ νλ‘νΌν° μμ± λ°©λ²λ μλ€.
μ¦, μΌλΆ νλ‘νΌν°λ₯Ό μ νμ μμλ‘ λ§λ€ μ μλ€.
νλ‘νΌν° λ€μ ?λ₯Ό λΆμ΄λ©΄λλ€.
type Point = {
x: number;
y: number;
z?: number; // μ νμ νλ‘νΌν°
}
const myPoint: Point = {x: 1,y: 2}; // compile
κ°μ²΄ λ΄μ νΉμ νλ‘νΌν°λ₯Ό νμνκ±°λ λ°°μ΄μ΄λ ν΄λμ€μ μ κ·Όν λ μ¬μ©λλ©°
κ°μ²΄μ νλ‘νΌν°λ₯Ό readonlyλ‘ νμνλ©΄ TypeScriptμμλ νλ‘νΌν°λ₯Ό λ³κ²½ν λ κ²½κ³ λ₯Ό ν΄μ€λ€.
type User = {
readonly id: number;
username: string;
};
const user: User = {
id : 123,
username : "catgurl"
}
console.log(user.id); // compile
user.id = 789; // error
2κ° μ΄μμ νμ μ κ΅μ°¨νμ¬ μ¬μ©ν μ μλ€.
type Circle = {
radius : number;
}
type Colorful = {
color : string;
}
type ColorfulCircle = Circle & Colorful;
const happyFace: ColorfulCircle = {
radius: 4,
color: "yellow"
};