Interface
1. 객체의 스펙 (속성과 속성의 타입)
2. 함수의 파라미터
3. 함수의 스펙 (파라미터, 반환 타입 등)
4. 배열과 객체에 접근하는 방식
5. 클래스
//interface 추가하여 함수 매개변수 프로퍼티를 정의
interface Person {
name: string
}
function sayName(obj: Person) {
console.log(obj.name);
}
let person = { name: "june" };
sayName(person);
Properties
✔️ Optional Properties
프로퍼티 선언시 이름 끝에 ?을 붙여 표시
interface SquareConfig {
color?: string
width?: number
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = { color: "white", area: 100 };
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" })
//width 설정 안해도 optional이기 때문에 에러발생x
✔️ readonly properties
객체가 처음 생성될때 설정하고 이후 수정 불가능
interface Point {
readonly x: number
readonly y: number
}
let point: Point = { x: 10, y: 20 };
point.x = 5;
// Cannot assign to 'x' because it is a read-only property.
✓✓ readonly vs const
둘다 생성 후에 배열을 변경하지 않음
const->변수 / readonly->프로퍼티
Interface type
함수
-자바스크립트 객체가 가질 수 있는 넓은 범위의 형태 기술
-프로퍼티로 객체를 기술하는 것 외에도 함수타입 설명 가능
클래스
-클래스가 특정 통신 프로토콜을 충족하도록 명시적으로 강제
▶function type
-함수 인자의 타입과 반환 값의 타입을 정의
-함수의 타입을 정의
▶class type
-클래스가 특정계약을 충족하도록 명시적으로 강제
▶interface 확장
-인터페이스 간의 확장 가능(클래스와 유사)
▶hybrid type
-여러가지 타입을 조합 가능