/**
* Type
*
* 타입은 쉽게 말해서 TS의 타입에 이름을 지어주는 역할을 한다.
*
*/
type NewStringType = string; // let, const처럼 TS에서는 type라는 것을 사용할 수 있고 NewStringType은 string타입이다.
type NewNullType = null;
type NewNumberType = number;
type MaleOrFemail = 'male' | 'female'; // male 또는 female
const stringVar : string = 'test';
const stringVar1 : NewStringType = 'test1';
type IdolType = {
name: string;
year: number;
}; //IdolType이라는 타입은 오브젝트인데 name과 year가 존재해야한다.
const yuJin: {
name:string;
year:number;
} = {
name:'안유진',
year : 2002,
} //IdolType을 사용하지 않고 그냥 쓸 때 복잡함 매번 타입을 선언해야함
const yuJin2: IdolType = {
name:'안유진',
year : 2002,
} //IdolType을 사용함 간단하게 사용
타입스크립트에서만 사용할 수 있다. type은 type을 변수로 만들 수 있는데
type NewStringType = string을 하면 NewStringType은 곧 string타입과 같게 된다.
type도 객체처럼 사용할 수 있다.
/**
* Interface
*
*
*/
interface IdolInterface{
name: string;
year: number;
}
const yuJin3 : IdolInterface = {
name:'안유진',
year : 2002,
}
interface IdoITF{
name : NewStringType;
year : NewNumberType;
}
const yuJin4 : IdoITF = {
name:'안유진',
year : 2002,
}
interface IdolOptional{
name:string;
year?: number;
} //?을 사용하면 입력을 해도되고 안해도 된다
const yuJin5 : IdolOptional = {
name:'안유진',
}
type과 interface와 비슷하게 사용할 수 있다. 하지만 차이점이 있다.
interface는 확장이 가능하고 함수사용도 가능하다.
{
// 인터페이스를 사용할 때, 같은 이름의 인터페이스는 자동 병합된다.
interface PrintName {
(name: string): void;
}
interface PrintName {
(name: number): void;
}
// ✅
const printName: PrintName = (name: number | string) => {
console.log('name: ', name);
};
}
{
// 타입을 사용할 때, 그것은 유일 해야하고, 오직 &를 사용해야만 병합 가능하다.
type PrintName = ((name: string) => void) & ((name: number) => void);
// ✅
const printName: PrintName = (name: number | string) => {
console.log('name: ', name);
};
}
확장에서의 차이 => interface는 extends를 type에서는 &를 이용해 상속을 통한 확장을 진행한다.
interface interface1 {
a: string;
}
interface interface2 extends interface1 {
b: string;
}
const interfaceConst: interface2 = {
a: 'a',
b: 'b'
}
type type1 = {
a: string;
}
type type2 = type1 & {
b: string;
};
const typeConst: type2 = {
a: 'a',
b: 'b',
}