-
TS 인터페이스JavaScript/TypeScript 2021. 6. 19. 02:52
인터페이스 (Interface)
- 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용한다
- 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다
- 인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점이 클래스와 유사하나
- 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드이다 (abstract 키워드는 사용하지 않는다)
interface Person1 { name: string; age: number; } function hello1(person: Person1): void { console.log(`이름: ${person.name} 나이: ${person.age}`); } const p1: Person1 = { name: 'Yoo', age: 27, }; // 이름: Yoo 나이: 27 hello1(p1);
optional property
// name은 필수 속성, age는 선택 속성 (?사용) interface Person2 { name: string; age?: number; } function hello2(person: Person2): void { console.log(`안녕하세요! ${person.name} 입니다.`); } // 안녕하세요! Yoo 입니다. hello2({name: 'Yoo', age: 39}); // 안녕하세요! LEE 입니다. hello2({name: 'LEE'});
// indexable types - 동적으로 Object에 property 추가 // [ key : KeyType ] : PropertyType 형식으로 interface 안에 선언 interface Person3 { name: string; age?: number; [index: string]: any; } function hello3(person: Person3): void { console.log(person); } const p31: Person3 = { name: 'Yoo', age: 25, }; const p32: Person3 = { name: 'Lee', systers: ['Sung', "Chan"], }; const p33: Person3 = { name: 'Park', father: p31, mother: p32, }; // { name: 'Yoo', age: 25 } hello3(p31); // { name: 'Lee', systers: [ 'Sung', 'Chan' ] } hello3(p32); // { // name: 'Park', // father: { name: 'Yoo', age: 25 }, // mother: { name: 'Lee', systers: [ 'Sung', 'Chan' ] } // } hello3(p33);
function in interface
// 인터페이스 안에서 함수 선언 interface Person4 { name: string; age: number; hello(): void; } // 인터페이스 함수 구현1 const p41: Person4 = { name: 'Yoo', age: 27, hello: function(): void { console.log(`${this.name} 입니다.`) } }; // 인터페이스 함수 구현2 const p42: Person4 = { name: 'Lee', age: 25, hello(): void { console.log(`${this.name} 입니다.`) } }; // 인터페이스 함수 구현3 // const p43: Person4 = { // name: 'Yoo', // age: 27, // hello: (): void => { // console.log('화살표 함수는 this 사용 불가') // } // }; // Yoo 입니다. p41.hello(); // Lee 입니다. p42.hello();
class implements interface
interface IPerson1 { name: string; age?: number; hello(): void; } // 인터페이스에서 선언한 것을 구현 class Person implements IPerson1 { name: string; age?: number | undefined; // 생성자 함수 constructor(name: string) { this.name = name; } hello(): void { console.log(`${this.name} 입니다.`); } } const person: IPerson1 = new Person('Yoo'); // Yoo 입니다. person.hello();
interface extends interface
interface Iperson2 { name: string; age?: number; hello(): void; } // 인터페이스 상속 interface IKorean extends Iperson2 { city: string; } const k: IKorean = { name: 'Yoo', city: 'Seoul', hello(): void { console.log(this); } }; // { name: 'Yoo', city: 'Seoul', hello: [Function: hello] } k.hello();
function interface
// 인터페이스로 함수 표현 interface HelloPerson { (name: string, age?: number): void; } const helloPerson: HelloPerson = function (name: string) { console.log(`${name} 입니다.`) }; // Yoo 입니다. helloPerson('Yoo', 27);
Readonly Interface Properties
// readonly - 읽을 수는 있지만 쓸 수는 없다 // 생성된 타입의 프로퍼티는 재할당할 수 없다 interface Person8 { name: string; readonly age: number; } const p81: Person8 = { name: 'Yoo', age: 27, }; // p81.age = 28; (에러 발생)
type alias vs interface
// type alias vs interface ///////////////////////////////////////////////////// // Function // type alias type EatType = (food: string) => void; // interface interface IEat { (food: string): void; } ///////////////////////////////////////////////////// // Array // type alias type PersonList = string[]; // interface interface IPersonList { [index: number]: string; } ///////////////////////////////////////////////////// // Intersection interface ErrorHandling { succes: boolean; error?: { message: string}; } interface ArtistsData { artists: { name: string }[]; } // type alias type ArtistsResposeType = ArtistsData & ErrorHandling; // interface interface IArtistsResponse extends ArtistsData, ErrorHandling {} let art: ArtistsResposeType; let iar: IArtistsResponse; ///////////////////////////////////////////////////// // Union types interface Bird { fly(): void; layEggs(): void; } interface Fish { swim(): void; layEggs(): void; } // type alias type PetType = Bird | Fish; // interface // interface IPet extends PetType {}; (에러 발생) // class // class Pet implements PetType {}; (에러 발생) /////////////////////////////////////////////////////
// Declaration Merging - interface interface MergingInterface { a: string; } interface MergingInterface { b: string; } let mi: MergingInterface; // mi.a , mi.b // type alias는 불가능
'JavaScript > TypeScript' 카테고리의 다른 글
TS Generics (0) 2021.06.23 TS 클래스 (0) 2021.06.23 TS 컴파일러 (0) 2021.06.18 TS 타입 시스템 (0) 2021.06.17 TS 타입 (0) 2021.06.12