🌐 FrontEnd/TypeScript

TypeScript νƒ€μž…μŠ€ν¬λ¦½νŠΈ 기초 -2

m-ur-phy 2022. 11. 8. 20:33

μ‹œμž‘ν•˜λ©΄μ„œ

νƒ€μž…μŠ€ν¬λ¦½νŠΈμ˜ 기초λ₯Ό κ³΅λΆ€ν•©λ‹ˆλ‹€.

 

클래슀 μ •μ˜

  • ν΄λž˜μŠ€λŠ” implements λ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€.
  • ν΄λž˜μŠ€λŠ” 객체와 λΉ„μŠ·ν•΄λ³΄μ΄μ§€λ§Œ, 상속을 ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
// TS

interface Car{
    color:string;
    wheels:number;
    start():void;
} // μƒμ„±μž(constructor) κΉŒμ§€λŠ” control ν•  수 μ—†λ‹€

class Bmw implements Car{ // ':' 말고 implements λ₯Ό μ‚¬μš©ν•΄μ•Όν•œλ‹€
    color; // TS μ—μ„œ μƒλž΅ν•˜κ²Œ 되면 BMW μ•ˆμ˜ colorλ₯Ό μ°Ύμ§€ λͺ»ν•œλ‹€. λ³€μˆ˜λ₯Ό κΌ­ λ§Œλ“€μ–΄ μ£Όμ–΄μ•Όν•œλ‹€.
    wheels=4; // TS μ—μ„œ μƒλž΅ν•˜κ²Œ 되면 wheelsλ₯Ό μ°Ύμ§€ λͺ»ν•œλ‹€. BMW class 에 Wheels λ³€μˆ˜λ₯Ό λ§Œλ“€μ–΄ μ£Όμ–΄μ•Όν•œλ‹€.
    constructor(c:string){
        this.color=c;
    }
    start():void{
        console.log('go....!');
    }
}

const car1 = new Bmw('green');
console.log(car1);
car1.start();
// JS

class Bmw {
    constructor(c) { // constructor(μƒμ„±μž ν•¨μˆ˜)λŠ” μ²˜μŒμ— μžλ™μœΌλ‘œ μ‹œμž‘ (멀버 λ³€μˆ˜λ₯Ό μ΄ˆκΈ°ν™”ν•΄μ€€λ‹€)
        this.wheels = 4; // 멀버 λ³€μˆ˜
        this.color = c;
    }
    start() {
        console.log('go....!');
    }
}

const car1 = new Bmw('green'); // car1 은 μΈμŠ€ν„΄μŠ€
console.log(car1);
car1.start();

 

extends (ν™•μž₯)

interface Car{ // λΆ€λͺ¨ μΈν„°νŽ˜μ΄μŠ€
    color:string;
    wheels:number;
    start():void;
}

interface Car2 extends Car{ // μžμ‹ μΈν„°νŽ˜μ΄μŠ€
    door:number;
    stop(d:number):number;
}

// interface Car2{ // μžμ‹ μΈν„°νŽ˜μ΄μŠ€
//     color:string;
//     wheels:number;
//     door:number;
//     start():void;
//     stop():void;
// }

class Bmw implements Car{
    color;
    wheels=4;
    constructor(c:string){
        this.color=c;
    }
    start():void{
        console.log('Bmw go....!');
    }
}

const car1 = new Bmw('green');
console.log(car1);
car1.start();

class Benz implements Car2{
    color='red';
    wheels=4;
    door;
    constructor(c:number){
        this.door=c;
    }
    start():void{
        console.log('Benz go....!');
    }
    stop(d:number):number{
        console.log('Benz stop....!');
        this.door = d;
        return this.door;
    }
}

const car2 = new Benz(4);
car2.wheels = 10;
car2.color = 'gray';
car2.door = 100;
console.log(car2);
car2.start();

let aaa:number = 0;
aaa = car2.stop(200);
console.log(aaa);
// κ²°κ³Ό

[LOG]: Bmw: {
  "wheels": 4,
  "color": "green"
} 
[LOG]: "Bmw go....!" 
[LOG]: Benz: {
  "color": "gray",
  "wheels": 10,
  "door": 100
} 
[LOG]: "Benz go....!" 
[LOG]: "Benz stop....!" 
[LOG]: 200

 

extends (ν™•μž₯-2)

// interface Pro{
//     color:string;
//     wheels:number;
//     name:string;
//     price:number;

//     start():void;
//     open():void;
//     buy():void;
// }

interface Car {
    color:string;
    wheels:number;
    start():void;
}

interface Toy{
    name:string;
    open():void;
}

interface ToyCar extends Car, Toy {
    price:number;
    buy():void;
}

class Product implements ToyCar{
    color='red';
    wheels=4;
    name='doll';
    price=500;

    start():void{
        console.log('start....!');
    }
    open():void{
        console.log('open stop....!');
    }
    buy():void{
        console.log('buy stop....!');
    }
}

const person1 = new Product();

console.log(person1);
person1.start();
person1.open();
person1.buy();

 

ν•¨μˆ˜ νƒ€μž… μ •μ˜ 방법

예제 1

function add(num1:number , num2:number):number{
    return num1+num2;
}
console.log(add(10,20));  // 30

function isAdult(age:number):boolean{
    return age > 19;
}
console.log(isAdult(30));  // true

예제 2

  • λ§€κ°œλ³€μˆ˜λ₯Ό 전달해 μ£Όμ§€ μ•ŠλŠ”λ‹€λ©΄ TS λŠ” μ—λŸ¬κ°€ λ°œμƒν•©λ‹ˆλ‹€.
function hello(name:string):string{
    return `Hello, ${name || "world"}`; // name이 λ“€μ–΄μ˜€λ©΄ name 좜λ ₯, μ•„λ‹ˆλΌλ©΄ "world" λ₯Ό 좜λ ₯ν•˜λΌ
}

const result = hello();  // μ—λŸ¬λ°œμƒ
const result2 = hello('kim');
console.log(result, result2);
  • 이λ₯Ό 작기 μœ„ν•΄μ„œ 선택적 λ§€κ°œλ³€μˆ˜ ? λ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€.
// μ—λŸ¬κ°€ λ‚˜μ˜€μ§€ μ•Šκ²Œ μž‘μ„±ν•˜λ €λ©΄? 선택적 λ§€κ°œλ³€μˆ˜λ₯Ό μ΄μš©ν•˜μž!

function hello(name?:string){  // λ³€μˆ˜? -> 선택적 λ§€κ°œλ³€μˆ˜
    return `Hello, ${name || "world"}`;
}

const result = hello(); 
const result2 = hello('kim'); 
console.log(result, result2);
  • 선택적 λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  if문을 μ‚¬μš©ν•œλ‹€λ©΄?
function hello(name:string):string{
    if(name == undefined) {
        return `Hello, world`
    }else{
        return `Hello, ${name}`
    }
}
  • 선택적 λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  λ§€κ°œλ³€μˆ˜μ— 초기 값을 μ§€μ •ν•΄μ€˜μ„œ μ‚¬μš©ν•  μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€.
function hello2(name = 'world'):string{  // λ³€μˆ˜? -> 선택적 λ§€κ°œλ³€μˆ˜
    return `Hello, ${name}`;
}
const result3 = hello2(); 
const result4 = hello2('kim'); 
console.log(result3, result4);

 

λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜

function add(...nums:number[]):number {
    return nums.reduce((result, num) => result + num);
}

console.log(add(1, 2, 3)); // 6
console.log(add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); // 55

 

예제 4

interface User {
    name:string;
    age:number;
}

function join(name:string, age:number):User {
    return{
        name,
        age
    };
};

const person1:User = join('μ‹ ν˜•λ§Œ', 60);
console.log(person1); 
/*
{
  "name": "μ‹ ν˜•λ§Œ",
  "age": 60
} 
*/

/*
// interface 없이 직접 λͺ…μ‹œν•΄μ£ΌλŠ” 방법

function join(name:string, age:number):{name:string, age:number} {
    return{
        name,
        age
    };
};

const person1:{name:string, age:number} = join('μ‹ ν˜•λ§Œ', 60);
console.log(person1); 

*/

// this? κ°μ²΄λ‚˜ class μ—μ„œ μ‚¬μš©

ν™”μ‚΄ν‘œν•¨μˆ˜λ‘œ μˆ˜μ •

interface User {
    name:string;
    age:number;
}

interface Func {
    (name:string, age:number):User;
}

const join:Func = (name, age) => {
    return {
        name,
        age
    };
}

const person1:User = join('μ‹ ν˜•λ§Œ', 60);
console.log(person1);

 

λ¦¬ν„°λŸ΄(Literal types) / μœ λ‹ˆμ˜¨(Union types) / κ΅μ°¨νƒ€μž…(Intersection types)

λ¦¬ν„°λŸ΄

  • λ¦¬ν„°λŸ΄μ΄λž€? type을 μƒλž΅ν•˜λ”λΌλ„, μ΄ˆκΈ°κ°’μ— 따라 type이 κ³ μ •λœλ‹€λŠ” 것 즉, μ •ν™•ν•œ 값이 지정됨을 λ§ν•©λ‹ˆλ‹€.
  • λ¬Έμžμ—΄μ΄λ‚˜ μˆ«μžμ— μ •ν™•ν•œ 값을 μ§€μ •ν•œλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.

μœ λ‹ˆμ˜¨ → | (λ˜λŠ”)

  • μ—¬λŸ¬κ°œμ˜ 선택지λ₯Ό 쀄 수 μžˆλŠ” νƒ€μž…μž…λ‹ˆλ‹€.
const userName1 = 'Bob'; // type -> 'Bob' (μƒμˆ˜ 이기 λ•Œλ¬Έμ— κ°’ μžμ²΄κ°€ type이 λœλ‹€)
let userName2 = 'Tom';  // type -> string
let userName3: string | number;
userName3 = 'μœ λ‹¨μž';
userName3 = 100;
console.log(userName1, userName2, userName3);

type Job = "police" | "developer" | "teacher";

interface User{
    name : string;
    job : Job;
}

const user:User ={
    name : "Bob",
    job : "developer"   // job : "student" -> μ—λŸ¬
}
console.log(user.name, user.job);

κ΅μ°¨νƒ€μž… -> & (μ—¬λŸ¬κ°œμ˜ νƒ€μž…μ„ ν•˜λ‚˜λ‘œ ν•©μΉœλ‹€)

interface Car{
    name : string;
    start(): void;
}

interface Toy{
    name : string;
    color : string;
    price: number;
}

const toyCar : Toy & Car ={
    name: 'λ²„μŠ€',
    color: 'blue',
    price: 10000,
    start(){
        console.log(this.name, this.color, this.price+'원');
    }
}
toyCar.start(); // "λ²„μŠ€",  "blue",  "10000원"

 

class ES6 (클래슀 볡슡)

JS

  • μžλ°”μŠ€ν¬λ¦½νŠΈ(.js) μ—μ„œλŠ” 였λ₯˜κ°€ λ°œμƒν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
class Car{
    constructor(color){
        this.color = color;
    }
    start(){
        console.log(this.color + " car start!");
    }
}

const bmw = new Car("red");
bmw.start();

TS

  • .tsμ—μ„œλŠ” color λΆ€λΆ„μ—μ„œ 였λ₯˜ 3κ°œκ°€ λ°œμƒν•©λ‹ˆλ‹€.
  • 클래슀 λ§΄λ²„λ³€μˆ˜λ₯Ό κΌ­ 선언을 ν•΄μ£Όμ–΄μ•Ό ν•©λ‹ˆλ‹€.(.ts)
class Car{
    color: string;
    constructor(color: string){
        this.color = color;
    }
    start(){
        console.log(this.color + " car start!");
    }
}

const bmw = new Car("red");
bmw.start();

 

public μ‚¬μš©

public μ΄λž€? → μ „μ—­ μ΄λΌλŠ” 의미λ₯Ό κ°€μ§€κ³  μžˆμŠ΅λ‹ˆλ‹€.

class Car{
    // color: string;
    constructor(public color: string){ // constructor λ‚΄λΆ€μ—μ„œ public μ‚¬μš©
        this.color = color;
    }
    start(){
        console.log(this.color + " car start!");
    }
}

const bmw = new Car("red");
bmw.start();

 

readonly μ‚¬μš©(μ½κΈ°μ „μš©)

class Car{
    // color: string;
    constructor(readonly color: string){
        this.color = color;
    }
    start(){
        console.log(this.color + " car start!");
    }
}

const bmw = new Car("red");
bmw.start();
// bmw.color='red';   // μ—λŸ¬ : 읽기 μ „μš©μ΄λΌ 값을 λ°”κΏ€ 수 μ—†λ‹€
  • public / read-only λŠ” νŒŒλΌλ―Έν„°μ˜ μƒμˆ˜(const)λ₯Ό λ§Œλ“€μ–΄ μ£ΌλŠ” 것이라고 μƒκ°ν•˜λ©΄ 이해가 μ‰½μŠ΅λ‹ˆλ‹€.

 

⭐⭐⭐⭐⭐ μ ‘κ·Ό μ œν•œμž(Access Modifier) ⭐⭐⭐⭐⭐

  • public → μžμ‹ 클래슀, 클래슀 μΈμŠ€ν„΄μŠ€ λͺ¨λ‘ μ ‘κ·Ό κ°€λŠ₯ (μƒλž΅ν•˜λ©΄ κΈ°λ³Έκ°’)
  • private → ν•΄λ‹Ή 클래슀 λ‚΄λΆ€μ—μ„œλ§Œ μ ‘κ·Ό κ°€λŠ₯ (μžμ‹ 클래슀 μ‚¬μš© λΆˆκ°€)
  • protected → μžμ‹ν΄λž˜μŠ€μ—μ„œ μ ‘κ·Ό κ°€λŠ₯/ 클래슀 μΈμŠ€ν„΄μŠ€μ—μ„œ μ ‘κ·Ό λΆˆκ°€

클래슀 μΈμŠ€ν„΄μŠ€ → μ–΄μ©Œκ³  = new ddd → μ–΄μ©Œκ³ .name μ΄λŸ°μ‹μ˜ 접근이 λΆˆκ°€λŠ₯ν•©λ‹ˆλ‹€.

public

class Car{
    public name:string = "λ˜₯μ°¨";
    color:string;
    constructor(color:string){
        this.color=color;
    }
    public start(){ // ν•¨μˆ˜μ—λ„ public μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€
        console.log('λΆ€λͺ¨ν΄λž˜μŠ€ strat!!',this.name, this.color);
    }
}

class Bmw extends Car{
    constructor(color:string){
        super(color);
    }
    showName(){
       console.log('μžμ‹ν΄λž˜μŠ€ strat!!', this.name , this.color);  // λΆ€λͺ¨μ—κ²Œμ„œ 물렀받은 name, color (μžμ‹ ν΄λž˜μŠ€μ—μ„œλ„ μ‚¬μš©ν•  수 μžˆλ‹€)
    }
}

const mycar = new Bmw("red");
mycar.name="μƒˆμ°¨";  // μΈμŠ€ν„΄μŠ€μ—μ„œ 직접 값을 λ°”κΏ€ 수 μžˆλ‹€ (μΈμŠ€ν„΄μŠ€μ— μ ‘κ·Ό κ°€λŠ₯ν•˜λ‹€)

mycar.start(); // "λΆ€λͺ¨ν΄λž˜μŠ€ strat!!",  "μƒˆμ°¨",  "red" 
mycar.showName(); // "μžμ‹ν΄λž˜μŠ€ strat!!",  "μƒˆμ°¨",  "red"

private

class Car{
    private name:string = "λ˜₯μ°¨";
    color:string;
    constructor(color:string){
        this.color=color;
    }
    private start(){ // ν•¨μˆ˜μ—λ„ public μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€
        console.log('λΆ€λͺ¨ν΄λž˜μŠ€ strat!!',this.name, this.color);
    }
}

class Bmw extends Car{
    constructor(color:string){
        super(color);
    }
    showName(){
       console.log('μžμ‹ν΄λž˜μŠ€ strat!!', this.name , this.color);  // λΆ€λͺ¨μ—κ²Œμ„œ 물렀받은 name, color (μžμ‹ ν΄λž˜μŠ€μ—μ„œλ„ μ‚¬μš©ν•  수 μžˆλ‹€)
    }
}
const car = new Car("pink");
car.color = "blue";
console.log(car.color);

const mycar = new Bmw("red");
mycar.name = "μƒˆμ°¨";  // μ—λŸ¬ -> μžμ‹ ν΄λž˜μŠ€μ—μ„œ μ ‘κ·Όν•  수 μ—†λ‹€.
mycar.color = "green"

mycar.start(); // μ—λŸ¬ -> μžμ‹ ν΄λž˜μŠ€μ—μ„œ μ ‘κ·Όν•  수 μ—†λ‹€.
mycar.showName(); // "μžμ‹ν΄λž˜μŠ€ strat!!",  "μƒˆμ°¨",  "red"

protected

class Car{
    protected name:string = "λ˜₯μ°¨";
    color:string;
    constructor(color:string){
        this.color=color;
    }
    protected start(){
        console.log('λΆ€λͺ¨ν΄λž˜μŠ€ strat!!', this.name, this.color);
    }
}

class Bmw extends Car{
    constructor(color:string){
        super(color);
    }
    showName(){
        console.log('μžμ‹ν΄λž˜μŠ€ strat!!', this.name , this.color);  //μžμ‹ ν΄λž˜μŠ€μ—μ„œλ„ μ‚¬μš©ν•  수 μžˆλ‹€
        super.start();
    }
}
const car = new Car("pink");
car.color = "blue";

const mycar = new Bmw("red");
// mycar.name="μƒˆμ°¨";  // μ—λŸ¬ : μΈμŠ€ν„΄μŠ€μ—μ„œ 직접 값을 λ°”κΏ€ 수 μ—†λ‹€
// mycar.start();
mycar.showName();

 

μ œλ„€λ¦­

  • μ œλ„€λ¦­μ€ νŠΉμ • νƒ€μž…μ„ μ΄μš©ν•΄μ„œ ν…œν”Œλ¦Ώμ²˜λŸΌ ν•¨μˆ˜λ₯Ό λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€

ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜μ˜ 전달 인자의 νƒ€μž…μ΄ λ‹€λ₯Όλ•Œ…

function getSize(arr: number[]): number{
   return arr.length;
}

const arr=[1,2,3]; 
console.log(getSize(arr));  //3

const arr2 = ['a','b','c','d','e'];
console.log(getSize(arr2));  //μ—λŸ¬κ°€ λ°œμƒν•œλ‹€
  • μœ λ‹ˆμ˜¨ 방식을 μ‚¬μš©ν•˜λŠ” 방법
function getSize(arr: number[] | string[]): number{
   return arr.length;
}

const arr=[1,2,3]; 
console.log(getSize(arr));  // 3

const arr2 = ['a','b','c','d','e'];
console.log(getSize(arr2)); // 5
  • μ œλ„€λ¦­μ„ μ‚¬μš©ν•˜λŠ” 법
function ν•¨μˆ˜λͺ…<νƒ€μž…νŒŒλΌλ―Έν„°>(λ§€κ°œλ³€μˆ˜:νƒ€μž…νŒŒλΌλ―Έν„°):νƒ€μž…{}
function getSize<T>(arr: T[]):number{
    return arr.length;
}

const arr = [1, 2, 3];
console.log(getSize<number>(arr));

const arr2 = ['a','b','c','d','e'];
console.log(getSize<string>(arr2)); 

const arr3 = [true,false,false,true];
console.log(getSize<Boolean>(arr3));

// any λ₯Ό μ“°λŠ” κ²½μš°λŠ”?? type scriptλ₯Ό μ“Έ μ΄μœ κ°€ μ—†λ‹€. κ·Έλƒ₯ vanila둜 μ“°λ©΄ λœλ‹€.
// <νƒ€μž…νŒŒλΌλ―Έν„°> -> <T>,<A>,<X>... 아무 κ°’μ΄λ‚˜ μ‚¬μš©κ°€λŠ₯ ν•˜λ‹€

μ œλ„€λ¦­ μ˜ˆμ‹œ 2

interface Mobile<T>{
    name: string;
    price: number;
    option: T;
}
/*
const obj1: Mobile<object> ={
    name: 'μ‚Όμ„± s20',
    price: 100,
    option: {
        color: 'red',
        coupon: false
    }
};
*/

const obj1: Mobile<{color:string; coupon:boolean}> ={
    name: 'μ‚Όμ„± s20',
    price: 100,
    option: {
        color: 'red',
        coupon: false
    }
};
console.log(obj1.name , obj1.price +'λ§Œμ›', '색상:'+obj1.option.color, '쿠폰:'+obj1.option.coupon);

const obj2: Mobile<string> ={
    name: 'μ‚Όμ„± s22',
    price: 120,
    option: 'android OS'
};
console.log(obj2.name , obj2.price +'λ§Œμ›', obj2.option);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

λ§ˆλ¬΄λ¦¬ν•˜λ©°

νƒ€μž…μŠ€ν¬λ¦½νŠΈμ˜ 기초λ₯Ό 1, 2νŽΈμ— κ±Έμ³μ„œ 곡뢀해 λ³΄μ•˜μŠ΅λ‹ˆλ‹€.

 

λ³€μˆ˜ λΏλ§Œμ•„λ‹ˆλΌ ν•¨μˆ˜κΉŒμ§€ λͺ¨λ“  곳에 νƒ€μž…μ„ μ§€μ •ν•΄μ€ŒμœΌλ‘œμ¨ 였λ₯˜λ₯Ό μ΅œμ†Œν™” ν•œλ‹€λŠ” 것이 λ§€λ ₯적으둜 λ‹€κ°€μ™”μŠ΅λ‹ˆλ‹€. μžλ°”μŠ€ν¬λ¦½νŠΈ μ„Έμƒμ—μ„œ κ°€μž₯ 많이 κ²ͺλŠ”μΌ "였λ₯˜λŠ” μ•ˆλœ¨λŠ”λ° 값이 μ•ˆλ‚˜μ™€μš”"κ°€ μ—†λŠ” νƒ€μž…μŠ€ν¬λ¦½νŠΈ! ν•œλ²ˆμ―€μ€ κΌ­ κ³΅λΆ€ν•΄λ³΄μ‹œλ©΄ 쒋을 λ“― μ‹ΆμŠ΅λ‹ˆλ‹€.

 

λŒ“κΈ€κ³Ό 곡감은 항상 ν™˜μ˜μž…λ‹ˆλ‹€!