[Typescript] 문법 정리
interface와 type 선언에 대해서 살펴봄
인터페이스 생성 및 사용
인터페이스interface IUser {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: IUser = new UserAccount("Murphy", 1);
- class UserAccount에서 name과 id 필드가 존재하므로 주어진 인터페이스를 만족함.
- 필드의 타입도 검증한다.
함수에서 인자나 반환타입을 명시할때는 아래와 같이...
인자, 반환타입
const user: IUser = new UserAccount("Murphy", 1);
/**
* 이름이 20글자가 넘는 사람을 골라내는 함수
*/
const filterWithLongName = (user:IUser) => user.name.length > 20;
1.1. 인터페이스 정의
Typescript interface
interface ILoc {
lat: number,
lng: number
};
class Hotel {
name:string;
id: number;
lat:number;
lng:number
constructor(id:number, name:string, lat:number, lng:number) {
this.name = name
this.id = id
this.lat = lat;
this.lng = lng;
}
}
class Busstop {
stationId:string;
lat:number;
lng:number;
constructor(stationId:string, lat:number, lng:number) {
this.stationId = stationId;
this.lat = lat;
this.lng = lng;
}
}
const members:ILoc[] = [];
members.push(new Hotel(98344,"awesome hotel", 12.3344, -135.1124));
members.push(new Hotel(47590,"so so beutiful hotel", 126.02993, 23.9013));
members.push(new Busstop("of283jf-sakkk2-gkk2k2", 123.3316, 11.93883));
- 인터페이스에 명시한 필드의 이름과 타입만 존재하면 서로 다른 클래스들도 하나의 배열에 담을 수 있음.
- lat, lng를 제외한 별도의 필드가 존재해도 괜찮다.
위와같은 인터페이스에 대해 object literal을 추가할 수도 있다.
Typescript interfacembers.push(new Hotel(47590,"so so beutiful hotel", 126.02993, 23.9013));
members.push(new Busstop("of283jf-sakkk2-gkk2k2", 123.3316, 11.93883));
members.push({lat: 123.3316, lng: 11.93883});
- lat, lng 필드가 정의되면 object literal로 허용함