[Typescript] Typescript 정리

seokki kwon·2022년 9월 27일
0

기본 타입선언

let num: string | number | object | any = 3;

배열

const arr: string[] = ['a'];
const arr: number[] = [3];

함수

function sum(x:number,y:number): number {
	return x + y;
}

number 타입의 숫자를 반환

class 예제

interface Shape {
    getArea():number;
}

class Circle implements Shape {
   
    constructor(public radius:number){
        this.radius = radius;
    }
    getArea() {
        return this.radius * this.radius * Math.PI;
    }
}

class Rectangle implements Shape {
    
    constructor(private width:number,private height:number) {
        this.width = width;
        this.height = height;
    }
    getArea(): number {
        return this.width * this.height;
    }
}

const circle:Circle = new Circle(5);

const rectangle:Rectangle = new Rectangle(20, 20);

function getCircleArea(circle:Circle) {
    return circle.getArea();
}

const shapes: Shape[] = [circle, rectangle];
shapes.forEach(shape=>{
    console.log(shape.getArea());
})

implement 를 사용하여 interface 상속가능

Generics

interface Person<T> {
	list:T
}

const Person:Person<string> = {
list : 'learn generics'
}

T라는 타입을 list에 할당가능

function merge<T1, T2> (a:T1, b:T2) {
	return {
      ...a,
      ...b,
    }
}

const merged = merge(2,'3');
function wrap<T> (param:T) {
	return {
      param
    }
}

const wrapped = wrap(20)

generics 는 언제?

타입이 동적이면서 타입을 지키고 싶을떄 사용을 한다.

profile
웹 & 앱개발 기록

0개의 댓글