티스토리 뷰
타입스크립트 Interface 코드 사용 예시
interface 키워드를 사용해 값이 특정한 형태(shape)를 갖도록 제약할 수 있다. 인터페이스를 정의하는 기본적인 문법은 객체 타입의 그것과 유사하다.
예제코드를 보면서 Interface의 활용법을 확인해보자.
@ 객체형Interface
type Score ='A' | 'B' | 'C' | 'F';
interface User{
name : string;
age : number;
gender? : string;
readonly birthYear: number;
[grade : number] : Score;
// 키값을 배열형태로 받을 수 있다.
// grade는 다른값으로 대체될 수 있음.
}
let user : User = {
name : 'xx',
age : 30,
birthYear : 2000,
// 배열 형태로 받은 키값을 아래와 같이 쓸 수 있다.
1 : 'A',
2 : 'B',
3 : 'C',
4 : 'F'
}
@ 함수형Interface
// 인자의 형식과, return 값의 형식을 지정해준다.
interface Add {
(num1 : number , num2 : number ): number;
}
const add : Add = function(x,y){
return x+y;
}
add(10,20); // 30
interface IsAdult {
(age : number) : boolean;
}
const a : IsAdult = (age) => {
return age > 19;
}
a(33); // true
@ Class형 Interface
class Bmw implements Car {
color;
wheels = 4;
// color를 입력받기 위함
constructor(c:string){
this.color = c;
}
start(){
console.log('go..')
}
}
const b = new Bmw('green');
console.log(b)
b.start()
// 출력
// Bmw: {
// "wheels": 4,
// "color": "green"
// }
// "go.."
@ Class형 Interface - extends를 이용한 확장
interface Car {
color : string;
wheels : number;
start() : void;
}
interface Toy {
name : string;
}
// 동시확장 가능
interface ToyCar extends Car, Toy {
price : number;
}
const myCar : ToyCar = {
color : 'red',
wheels : 5,
start(){
console.log('출발')
},
name : 'bmw',
price : 50000
}
'개발일기 > TS' 카테고리의 다른 글
[TS] Typescript 자주 사용되는 utility types정리 (0) | 2022.02.21 |
---|---|
[TS] Typescript Generic 예시코드. (0) | 2022.02.21 |
[TS] Typescript 추상클래스 (0) | 2022.02.21 |
[TS] Typescript 접근제한자 : public, private, protected + 정적메소드 static 예시 코드 (0) | 2022.02.21 |
[TS] Typescript 함수 오버로딩 예시 코드 (0) | 2022.02.21 |
댓글
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- React
- 전기산업기사
- 전기공사기사
- 전기기기
- 산업안전기사
- 개더타운
- cbt
- 전기기사실기단답
- TypeScript
- 전자기학
- 산업안전기사 실기
- zep
- dummydata
- 전기기사실기CBT
- gathertown
- 전력공학
- JavaScript
- TS
- 게더타운맵
- 실기CBT
- 전기기사
- 게더타운
- 전기기사필기
- 모두CBT
- 전기기사 필기
- shortid
- 산안기 합격률
- nextjs
- fakerjs
- KEC반영
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
글 보관함