Class
class User{
//생성자 매개변수에서 접근제어자(public, private, protected, readonly) 사용시
//속성 선언과 초기화 ts 자동으로 처리
constructor(
private name:string,
private number:number,
public nickName:string
){}
}
const aaa = new User("김고양",123,"애옹")
aaa.name; //에러
- private : 선언 클래스 내에서만 접근 가능
- protected : 선언 클래스, 자식 클래스에서 접근 가능
- public : 모든 클래스에서 접근 가능
class User {
private name: string;
private number: number;
public nickName: string;
//접근제어자 없을경우 명시적 초기화 필요
constructor(name: string, number: number, nickName: string) {
this.name = name;
this.number = number;
this.nickName = nickName;
}
}
추상 클래스,메서드
abstract 키워드를 사용
1. 추상 클래스
- 추상메서드 포함할 수 있는 클래스
- 객체 생성 불가
- 상속(extends) 통해 확장, 구체적인 메서드와 속성을 제공 가능
2. 추상메서드
- 구현부 없음. call signature만 작성
- 반드시 상속받은 클래스에서 구현해야함
//추상클래스
abstract class User{
constructor(
public name:string,
public number:number,
public nickName:string
){}
private getInfo(){
return `${this.name}, ${this.number}`
}
//추상메서드
abstract getNickName():void //Call Signature만가짐 구현부x
}
//extends 통해 상속
class Player extends User{
//상속받아 추상메서드 반드시 구현
getNickName(){
console.log(this.nickName);
}
}
const aaa = new Player("김고양",123,"애옹");
aaa.getInfo() //에러
interface
객체Object의 구조 정의
상속(extends), 병합, 구현(implements) 가능
interface User{
name: string
age: number;
}
//같은이름 interface선언시 병합 가능
interface User{
num: number;
}
const aaa:User = {
name: "김야옹",
age: 22,
num: 1234
}
//상속 가능
interface Player extends User{
color: string;
play(): string; // 메서드의 시그니처만 정의 (구현 X)
}
//클래스 구현
class Meow implements Player{
name: string;
age: number;
num: number;
color: string;
constructor(name: string, age: number, num: number, color: string){
this.name = name;
this.age = age;
this.num = num;
this.color = color;
}
play(): string {
return `${this.name}!!`;
}
}
*${}
표현식 삽입할때 사용
변수(this.fistName), 표현식(a+b),함수호출${greet("Kim")}
type과 비슷함
type User = {
name: string,
team: Team
}
interface User1{
name: string,
team: Team
}
//const aaa:User = {
const aaa:User1 = {
name : "김야옹",
team : "blue"
}
type? interface?
| type | interface | |
| 정의 | 객체 외에도 다양한 타입(함수, 배열, 특정값, |타입) 정의 | 객체 구조 정의 |
| 확장 | 교차 가능 | 상속, 병합, 구현 가능 |
//type : 객체 구조외에도 정의 가능
//함수 타입(매개변수,반환 타입 정의)
type AddFunction = (a: number, b: number) => number;
const add: AddFunction = (a, b) => a + b;
//배열타입
type StringArray = string[];
const fruits: StringArray = ["Apple", "Banana"];
//특정값(리터럴 타입)
type Team = "blue" | "white"
const team:Team = "blue"
//|유니언 타입
type ID = string | number;
const user1: ID = 123;
const user2: ID = "abc";
//교차가능
type User = {
name: string;
age: number;
}
type Player= {
color: string;
}
type Full = User & Player;
const aaa:Full = {
name: "김야옹",
age: 22,
color: "blue"
}
∴객체 구조 정의시 interface 그외엔 type 추천
'TypeScript' 카테고리의 다른 글
| [TypeScript] Enums(열거형) (0) | 2024.12.23 |
|---|---|
| [TypeScript] Call Signatures / Over Loading / Generics (0) | 2024.11.30 |
| [TypeScript] 기본타입 (0) | 2024.11.29 |
| [TypeScript] 타입 선언/ 별칭/ 옵션 (0) | 2024.11.28 |
| [TypeScript] 설치 및 환경 구축 (0) | 2024.11.27 |