지금까지 타입을 선얼할 때 concrete type 선언을 통해 아래와 같이 작성하는 법만 공부했다.
type Team = string;
type Player = {
nickname: string,
team: Team
};
const funco:Player = {
nickname : "funco",
team : "red"
};
좀 더 강한 제약을 주기 위해 아래와 같이 team 명에 들어올 수 있는 값들을 특정할 수 있다.
type Team = "red" | "blue" | "white";
type Player = {
nickname: string,
team: Team
};
const funco:Player = {
nickname : "funco",
team : "red" // "red" or "blue" or "white" only available
};
type color = string
과 같은 타입지정엔 쓸 수 없다.type Team = "red" | "blue" | "white";
interface Player {
nickname: string,
team: Team
};
const funco:Player = {
nickname : "funco",
team : "red"
};
interface Player {
nickname: string,
team: string
};
interface User extends Player {
}
const funco:User = {
nickname : "funco",
team : "red"
};
type Player = {
nickname: string,
team: string
};
type User = Player & {
} // & 을 사용한 type의 상속
const funco:User = {
nickname : "funco",
team : "red"
};
interface Player {
nickname : string
}
interface Player {
team : string
}
interface Player {
age : number
}
const funco:Player = {
nickname : "funco",
team : "red",
age : 32 // if funco don't have 'age' property => error
};
user
와 이를 상속받은 Player
클래스를 만들었다.abstract class User {
constructor (
protected firstName : string,
protected lastName : string
){}
abstract sayHi(name:string) : string
abstract fullName():string
}
class Player extends User{
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name:string){
return `Hi ${name}? my name is ${this.fullName()}`
}
}
위 코드는 아래의 JS 코드로 변환된다.
Interface
를 상속받은 Player
클래스를 만들었다.interface User {
firstName : string,
lastName : string
sayHi(name:string) : string
fullName():string
}
class Player implements User{
constructor(
public firstName:string,
public lastName:string
){}
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name:string){
return `Hi ${name}? my name is ${this.fullName()}`
}
}
위 코드는 아래의 JS 코드로 변환된다.
private
프로퍼티는 사용할 수 없다.