09009
[TypeScript] 인터페이스, 함수 본문
인터페이스
아래와 같이 코드 작성 시 에러 발생
에러 발생 : object에는 특정 속성 값에 대한 정보가 없기 때문
property를 정의해서 객체를 표현하고자 할때는 인터페이스를 사용한다.
위의 코드에서 성별은 Optional로 처리헤보면 아래와 같은 결과가 나온다.
(입력을 해도 되고 안해도 되는 속성은 변수명 뒤에 ?를 붙인다)
readonly 속성 붙이기
기존 코드
readonly 속성 붙이면 읽기 전용이라 수정할 수 없음.
학년별 성적 속성 추가 시, 아래와 같이 코드를 작성하면 에러가 발생한다.
아래 코드로 변경하면 에러는 발생하지 않지만 이는 적합한 코드가 아니다.
아래 코드로 작성하는 것이 바람직함
Add 인터페이스 예시 작성
boolean
interface Add {
(num1:number, num2:number): number;
}
const add : Add = function(x, y) {
return x + y;
}
add(10, 20);
interface IsAdult {
(age:number):boolean;
}
const a:IsAdult = (age) => {
return age > 19;
}
a(33); // true
인터페이스로 클래스도 정의 가능
생성자 사용해보기
입력
interface Car {
color: string;
wheels: number;
start(): void;
}
class Bmw implements Car {
color;
wheels = 4;
constructor(c:string) {
this.color = c;
}
start() {
console.log('go...');
}
}
const b = new Bmw('green');
console.log(b);
b.start();
// 인터페이스는 확장 가능
interface Benz extends Car {
// door, stop()을 추가로 정의 가능
door: number;
stop(): void;
}
// 모두 입력해주어야 에러 발생 x
const benz : Benz = {
door: 5,
stop() {
console.log('stop');
},
color: 'black',
wheels: 4,
start() {
console.log('go...');
}
}
출력
Bmw: {
"wheels": 4,
"color": "green"
}
"go..."
함수
기본 형태
function add(num1: number, num2: number) : number {
return num1 + num2;
}
function isAdult(age: number): boolean {
return age > 19;
}
아래와 같이 작성 시 에러
형태를 void로 변경해주면 된다.
인터페이스처럼 함수의 매개변수도 optional로 지정 가능
수정 코드
function hello(name: string, age?: number) : string {
if (age !== undefined) {
return `hello, ${name}. You are ${age}.`;
} else {
return `hello, ${name}`;
}
}
console.log(hello('Mbappe'));
console.log(hello('Mbappe', 25));
선택적 매개변수가 필수 매개변수보다 앞에 오면 에러가 발생한다.
택적 매개변수를 앞에 두고 사용하고 싶다면 아래와 같이 코드를 작성해야 한다.
...를 사용하면 전달받은 매개변수를 배열로 나타낼 수 있게 한다.
function add(...nums: number[]) {
return nums.reduce((result, num) => result + num, 0);
}
add(1, 2, 3); // 6
add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 55
This 키워드
아래 코드는 this 타입이 결정되지 않아서 에러 발생
타입스크립트에서 this의 타입을 정하려면 아래와 같이 지정한다.
매개변수가 있을 경우
아래 함수는 전달받은 매개변수의 타입에 따라 return 해주는 결괏값이 달라진다.
아래 객체들에서 에러가 발생하는데 User 객체를 반환하거나 string을 반환하는데 확신이 없기 때문에 그런 것이다.
이런 경우는 함수 오버로드를 사용한다.
전달받은 매개변수의 개수나 타입에 따라 다른 동작을 하게 하는 것
동일한 함수지만 매개변수의 타입이나 개수에 따라 다른 방식으로 동작하게 하려면 함수 오버로드를 사용하면 된다.
Union Types
// Union Types
interface Car {
name: "car";
color: "string";
start(): void;
}
interface Mobile {
name: "mobile";
color: string;
call(): void;
}
function getGift(gift: Car | Mobile) {
console.log(gift.color);
if (gift.name === "car") {
gift.start();
} else {
gift.call();
}
}
Intersection Types
필요한 모든 기능을 가진 하나의 타입
'Front-End > Typescript' 카테고리의 다른 글
[TypeScript] 기본 타입 (0) | 2024.05.20 |
---|