Web Front-end 공부/TypeScript

[TypeScript] Interface와 Type Alias

Hanachoi 2023. 2. 27. 10:35

 

  • Structural type system : 타입스크립트에서느 구조가 같으면 같은 타입으로 취급된다. 
// interface와 type의 모양(구조)가 같으면 같은 타입으로 인식된다. 
interface IPerson{
	name : string;
    age : number;
    speak(): string;
}

type PersonType ={
	name : string;
    age: number
    speak(): string;
}

let personInterface : IPerson = {} as any ;
let personType : PersonType = {} as any;

personInterface = personType;
personeType = personInterface;
  • nominal type system : 구조가 같아도 이름이 다르면, 다른 타입으로 취급된다
  • 규모가 큰 프로젝트라면 시도해볼만한 방법이다. 형태가 같더라도 이름을 기반으로 다른 타입으로 처리를 해줄 수가 있다.
  • 원래는 타입스크립트에서 제공하지 않는 시스템이지만 꼼수를 이용해 이렇게 적용 가능하다. 
type PersonID = string & { readonly brand: unique symbol}

function PersonID(id: string): PersonID{
	return id as PersonID;
}

function getPersonByid(id: personID){}

getPersonById(PersonID('id-aaaaa'))
getPersonById('id-aaaaa') // 타입이 string이긴 해도 이렇게 직접적으로 넣으면 에러 발생
  • function
  • 이름을 붙이는 형식만 다르다.
//type alias
type EatType = (food: string) => void;

//interface
interface IEat {
	(food: string): void;
}
  • array
//type alias
type PersonList = string [];

//interfce
interface IPersonList {
	[index : number]: string ;
}
  • intersection
interface ErrorHandling {
	success : boolean;
    error? : {message: string};
}

interface ArtistsData {
	artists: {name : string}[];
}

//두개의 인터페이스를 합쳐준다. 

//type alias 
type ARtistResponseType = Artistata & ErrorHandling;

//interface 
//두개의 interface를 extends 해와서 합쳐준다.
interface IArtistResponse extends ARtistsData, ErrorHandling {}

let art : ARtistsResponseType;
let iar : IArtistsResponse;
  • union types  : 변수의 값이 여러 타입을 가지는 경우 주로 사용됨. 
예를들어, 변수 age에는 숫자형이 들어와야하지만, 브라우저나 백앤드에서 값이 문자열로 들어오는 경우, 변수 age는 string 타입이 가능해야 한다. 이때 유니언타입을 사용한다. 
Union type은 파이프( | ) 기호를 사용해 정의한다
출처 : https://developer-talk.tistory.com/354
 

[TypeScript]유니온 타입(Union Type)

Union Type Union Type은 TypeScript의 기능 중 하나이며 변수의 값이 여러 타입을 가지는 경우 주로 사용됩니다. 예를 들어서 변수 age는 나이를 의미하며 나이는 숫자이므로 number 타입으로 정의할 수 있

developer-talk.tistory.com

interface Bird {
	fly() : void;
    layEggs(): void;
}

interface Fish {
	swim(): void;
    layEggs():void;
}

type PetType = Bird | Fish;
// type alias로 사용이 가능


// interface에서 extends 하거나 class에서 implement 하는 형태에선 지원안됨
interface IPet extends Pet type {}  //error
class Pet implements PetType {}  //error
  • Declaration Merging : 기본적으로 선언을 Merge 할수 있는 기능은 interface에서만 제공된다.
  • type alias에서는 에러가 발생한다. 
interface MergingInterface {
	a: string;
}

interface MergingInterface{
	b: string;
}

let mi : MergingInterface : mi // 타입이 a, b 둘다 가능해짐