인터페이스
인터페이스를 사용하는 이유
• 타입이 객체인 p1, p2, p3 객체를 생성하는 예
인터페이스를 사용하는 이유
🤔 코드마다 중복되는 객체 타입을 하나로 만들 수 있다면?
인터페이스
특징
• 코드의 재사용성을 높임
• 작성중인 코드에 대한 더 많은 정보를 타입스크립트에 제공하기 위해 사용
- 인터페이스는 자바스크립트 코드로 컴파일 되지 않음
이름 규칙
• 첫글자를 대문자로 표기
• 인터페이스 이름 앞에 대문자(I)를 붙이지 않음
인터페이스
• 객체의 타입을 지정
• 예시
인터페이스
타입이 인터페이스인 p1, p2, p3 객체를 생성하는 예
실습) 인터페이스
function App() {
interface Language{
name : string;
level : number
completed? : boolean
}
//인터페이스가 정해놓은 구조를 무조건 따라야 함
let p1: Language = {
name: "react",
level: 5
};
// let p2: Language = { name: "typescript" };
// let p3: Language = { level: 5 };
// let p4: Language = {};
let p5: Language = {
name: "javascript",
level: 1,
completed: true };
return (
<>
</>
);
}
선택 속성
• 필수 속성이 아닌 경우
• 속성 이름 뒤에 물음표(?) 기호를 붙임
interface 인터페이스이름 {
속성이름?: 속성타입
}
실습) 선택 속성
App.tsx
function App() {
interface Language {
name: string;
level: number
completed?: boolean //선택속성
}
let p1: Language = {
name: "react",
level: 5
};
let p2: Language = {
name: "javascript",
level: 1,
completed: true
};
return <div></div>;
}
export default App;
Type Alias vs Interface
선언 방식
• type
type UserType = {
name: string;
age: number;
}
• interface
interface UserInterface {
name: string;
age: number;
}
인터페이스는 오로지 객체만 가능 (any, union 불가능)
구현(implements)
• type
class User1 implements UserType {
}
• interface
class User2 implements UserInterface {
}
둘 다 클래스로 구현(implements) 가능
선언적 확장
동일한 이름으로 재선언할 경우 자동으로 하나로 합쳐짐
type
• 선언적 확장 불가능
type AddType = UserType & { address: string };
→ &연산을 이용하여 속성을 추가해야함
interface
• 선언적 확장 가능
interface UserInterface {
address: string;
}
→ 재선언 가능 (변수라고 생각하면 불가능인데 인터페이스는 가능) (자동으로 하나로 합쳐짐)
상속(extends)
• interface
interface AddInterface extends UserInterface {
gender: string;
}
클래스
클래스 선언문
class 클래스이름 {
속성이름: 속성타입 (함수도 가능)
}
예시
class Person {
name: string
age: number
}
생성자
• constructor() 메서드
실습) 클래스
ClassComponent.tsx
const ClassComponent = () => {
class Person{
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let p1: Person = new Person("soo", 20 );
console.log(p1);
return (
<div>
</div>
);
};
export default ClassComponent;
실행 결과
접근제한자
• 속성 이름 앞에 접근제한자를 붙일 수 있음
- public, private, protected
• 생략 시, public으로 적용
class Person {
name: string; // public 적용
private age: number;
}
private_age : private변수라고 선언할 때 기본적으로 언더바 붙임 (가독성을 위해 꼭 그래야할 필요는 없음)
public : 클래스 내부, 외부 o
private : 클래스 내부 o, 외부x,
protected : 클래스 내부 x, 외부x
인터페이스 구현
주의사항
• 인터페이스는 어떠한 속성이 있는지에 대한 규약
• 해당 속성을 생성해주지는 않음 (누가 구현 ? 클래스가 구현해줘야함)
- 인터페이스는 어떤 속성이 있는지 알려만 줄 뿐
• 따라서 클래스 내부에서 해당 속성을 정의해야 함
실습) 인터페이스 구현
App.tsx
interface PersonInterface {
name: string;
age: number;
}
class Person implements PersonInterface {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let p1: Person = new Person("soo", 20);
console.log(p1);
실행 결과
Person {name: 'soo', age: 20}
함수를 갖는 경우에는 함수 껍데기만 가지고 잇어야 함
interface NewInterface {name : string;age : number;
함수도 넣을 수 있다 (대신 구현은 x)함수1(){}함수2(){}
class Person implements NewInterface{name : string;age : number;
추상 클래스
추상화
• 의미
- 여러가지 사물/개념에서 공통되는 특성을 묶어 이름을 붙이는 것
• 공통된 메서드, 속성을 묶어 하나의 클래스로 생성
추상 클래스(abstract class)
• 완전하게 구현되어 있지 않은 메서드(추상 메서드)를 갖는 클래스
- 추상 클래스를 상속하는 클래스에서 추상 메서드를 구현해야 함
• 추상 클래스는 객체를 생성할 수 없음
- 메서드가 미완성이기 때문
• 목적
- 상속 계층에서 추상적인 개념을 나타내기 위해 사용
동물 상속 계층도
추상 클래스 선언문
추상클래스 {
일반메서드() { console.log("잠잔다")}
일반메서드() { console.log("잠잔다")}
추상메서드1()
추상메서드2()
추상메서드 한 개는 무조건 있어야 함
-> 객체 생성 불가능
실습) 추상 클래스
App.tsx
function App() {
// 추상 클래스 정의
abstract class AbstractPerson {
}
// 추상 클래스 상속
class Person extends AbstractPerson {
}
let p1: Person = new Person("soo", 20);
return <div></div>;
}
export default App;
function App() {
//추상 클래스 정의
abstract class AbstractPerson {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
info(): void {
console.log(`name : ${this.name}, age : ${this.age}`);
}
abstract say(): void;
}
function App() {
abstract class AbstractPerson {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
info(): void {
console.log(`name : ${this.name}, age : ${this.age}`);
}
abstract say(): void;
}
class Person extends AbstractPerson {
say() {
console.log("안녕하세요!");
}
}
let p1: Person = new Person("soo", 20);
p1.info();
p1.say();
return <>{/* <ClassComponent/> */}</>;
}
export default App;
매개변수 앞에 접근제한자 붙이면 this.어쩌구 생략 가능해짐
새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 9주차 블로그 포스팅
'Typescript' 카테고리의 다른 글
[새싹 프론트엔드] 9주차 - 5 제네릭 타입 (0) | 2022.12.16 |
---|---|
[새싹 프론트엔드] 9주차 - 3 TypeScript 함수 (0) | 2022.12.14 |
[새싹 프론트엔드] 9주차 - 3 TypeScript (0) | 2022.12.14 |