타입 별칭
; Primitive, Union Type, Tuple, Function 등 직접 작성해야하는 타입을 다른 이름으로 지정 가능
// primitive타입 별칭
type MyStringType=string;
let myStr:MyStringType='hello';
// Union 타입 별칭
type StringOrNumber=string|number;
let another:StringOrNumber='Anna';
// Tuple 타입 별칭
type A=[number,number];
let b:A=[1,2];
// Function 타입 별칭
type EatType=(food:string) => void;
Interfaces
; 하나의 타입을 만들어내는 방식
- 컴파일 시 사라짐(js파일에는 존재 x). 컴파일할 때만 필요함.
interface A{
a:a_type;
b:b_type;
}
const B : A = {
a:a',
b:b',
};
Optional Property
1. 상황에 따라 있을 수 있고 없을 수 있는 속성
interface A{
a:a_type;
b?:b_type; // Optional Property
}
2. 새로운 속성을 알아서 생성 가능 ( [index:type]:any; )
interface A{
a:a_type;
b?:b_type;
[index:c_string]:any; //어떤 속성이든 가능
}
const A':A={
a:a',
d:[d',d'],
};
const A'':A={
a:a',
e:e'',
f:f'',
};
// d,e,f는 모두 string형
함수를 Interface 내부에
interface A {
a:a_type;
b:b_type;
c(): void;
}
const A':A={
a:a',
b:b',
c:function():void{
console.log(`안녕하세요 제 이름은 ${this.a}입니다.`);
},
};
const A'':A={
a:a'',
b:b'',
c():void{ // function키워드 생략
console.log(`안녕하세요 제 이름은 ${this.a}입니다.`);
},
};
const A''':A={
a:a''',
b:b''',
c:(this:A):void => {
// 화살표 함수 내에서 화살표 함수 내에서 객체를 찾음 -> 없기 때문에 global this를 가리킴 => 사용 불가
console.log(`안녕하세요 제 이름은 ${this.a}입니다.`);
},
};
Class implements
class Class명 implements Interface명{
Interface 속성들 선언 (ex name:string )
}
interface A{
a:a_type;
b?:b_type;
c():void;
}
class B implements A{
a:a_type;
b?: b_type | undefined;
constructor(a:a_type, b?:b_type | undefined){ // name에 기본값을 할당해주어야함
this.a=a;
this.b=b;
}
c(): void {
console.log(`안녕하세요! ${this.a} 입니다.`);
}
}
const A':A = new B(a',b');
상속
; extends 사용
interface A{
a:a_type;
b?:b_type
}
interface B extends A{ // B는 A를 상속
c:c_type;
}
const B':B={
a:a',
b:b',
c:c',
};
Readonly
interface Person8{
name:string;
age?:number;
readonly gender:string;
}
const p81:Person8={
name:'Mark',
gender:"male",
};
p81.gender="female"; // 오류발생(gender는 readonly형이므로)
'WebProgramming > JS' 카테고리의 다른 글
[JavaScript] Computed Property (0) | 2022.07.26 |
---|---|
[JavaScript] Object Methods(assign,keys,values,entries,fromEntries) (0) | 2022.07.26 |
[JS] Array 메소드 (map,filter,reduce,find,concat,slice) (0) | 2022.07.15 |
[JS] JS 라이브러리 (lodash, axios) (0) | 2022.06.30 |
[TS] TS의 타입 시스템? & Compliation Context (0) | 2022.06.12 |
[TS] TypeSCript이란? & 타입 (0) | 2022.06.12 |
[JS] JSON (0) | 2022.06.11 |
[JS] 정규표현식 (0) | 2022.06.11 |