TypeScript
[타입스크립트] 타입의 종류와 인터페이스
메이플 🍁
2022. 11. 15. 15:37
타입의 종류
1. 오브젝트 모양 알려주기
type Player = {
nickname: string,
healthBar: number
}
2. 특정 타입이라고 지정해주기 (concrete type)
type Food = string
const kimchi:Food = 'delicious'
type Friends = Array<string>
const kakao:Friends = ['Ryan', 'Muzi', 'Apeach', 'Frodo']
3. alias(대체명, 별명)를 사용해 타입 지정해주기
type Nickname = string
type Health = number
type Player = {
nickname: Nickname,
healthBar: Health
}
4. 특정값을 지정
타입을 지정된 옵션으로만 제한
type Team = 'red' | 'blue' | 'yellow'
type Health = 1 | 5 | 10
type Player = {
nickname: string,
team: Team,
health: Health
}
const nico: Player = {
nickname: 'nico',
team: 'yellow',
health: 10
}
콘크리트 타입: 데이터의 타입을 하나로 지정하는 것
type Player = {
nickname: string, // nickname으로 올수있는 타입은 문자열뿐이다
}
5. 인터페이스
오직 오브젝트 데이터의 타입만을 지정할 수 있는 인터페이스를 사용한다
type Team = 'red' | 'blue' | 'yellow'
type Health = 1 | 5 | 10
interface Player {
nickname: string,
team: Team,
health: Health
}
const nico: Player = {
nickname: 'nico',
team: 'blue',
health: 1
}