interface

김수민·2023년 2월 16일
0

TypeScript

목록 보기
2/8

타입스크립트의 여러 객체를 정의하는 일종의 규칙, 구조

객체의 타입 정의

interface User{name:string, readonly age:number, isJob?:boolean}
let user2:User={
  	name: "blue",
  	age:20
}

✔ interface를 작성하면 type을 보다 간략하게 지정할 수 있다.
interface 작성시 key 앞에 readonly를 붙이면 읽기만 가능한 값, 변경 불가능한 값이 된다.
interface 작성시 key 뒤에 ?를 붙이면 반드시 작성하지는 않아도 되는 값이 된다.

interface Num1{
	1?:string,
	2?:string,
	3?:string,
	4?:string,
}
interface Num2{
	[grade:number]:string
}

✔ Num2의 key와 같이 interface의 key를[변수명:타입명]으로 지정하면,
interface를 타입으로 하는 변수의 key의 타입이 타입명일때 값을 string 타입으로만 작성할 수 있다.

type

type Score= 'A'|'B'|'C'|'D'|'E'|'F';
interface Student{
	testScore:Score
}

✔ 위와 같이 interface의 값으로 type 변수를 주면 그 변수의 값에 해당하는 값만을
interface를 타입으로 하는 변수의 key의 값이 testScore일때 값을 'A'|'B'|'C'|'D'|'E'|'F'로만 작성할 수 있다.


함수의 타입 정의

생성하는 방법

interface Add{
	(num1:number, num2:number):number;
//(매개변수:타입):return하는 값의 타입
}

적용시키는 방법

let myFunction5: Add =function(num1,num2){
	return num1+num2;
}

✔ interface를 작성하면 type을 보다 간략하게 지정할 수 있다.


클래스 타입에 interface 적용

implements이라는 키워드를 사용한다.

interface IStudetn{
	name: string,
	getName(): string
}

class Student2 implements IStudetn{
	name: string;
	constructor(name:string) {
		this.name=name;
		
	}
	getName():string{
		return this.name;
	}
}

인터페이스 extends

interface IAnimal{
	name:string;
}
interface ICat extends IAnimal{
	sound(): string;
}
class Cat implements ICat{
	name: string;
	constructor(name:string){
		this.name= name;
	}
	sound(): string {
		return "야용";
	}
}

interface도 class처럼 extends 키워드를 활용해 상속 할 수 있다.

interface IName{
	name: string;
	age: number;
}
interface IName{
	color: string;
}
const iname:IName={
	name:"A",
	age:40,
	color:"#fff"
}

같은 이름의 interface를 여러개 만들 수 있다.
기존에 만들어진 interface에 내용을 추가하는 경우 유용하다.

profile
sumin0gig

0개의 댓글