TypeScript 사용법

Seongkyun Yu·2021년 3월 7일
1

TIL - Typescript

목록 보기
1/1

기본 타입

const time: number = 12와 같은 형식으로 변수 선언 뒤에 :를 붙여 타입을 설정한다.

// boolean
const isDone: boolean = false;

// number
const decimal: number = 6;
const hex: number = 0xf00d;
const binary: number = 0b1010;
const octal: number = 0o744;

// string
const name: string = "Jhon Doe"

// void
function warnUser(): void {
    console.log("This is my warning message");
}

// array
let list: number[] = [1, 2, 3]; // 숫자로 구성된 배열

함수

const sum = (x:number, y:number):number => x+y의 형식으로 매개변수와 리턴값의 타입을 정해줄 수 있다.

const sum = (x:number, y:number):number => x+y

function hello(name: string):void {
  console.log(name, 'hello!')
}

interface

typescript에서는 interface를 활용하여 객체의 프로퍼티 타입을 미리 정해두고 변수처럼 사용할 수 있다.

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

단 interface 내의 프로퍼티들의 순서는 상관 없다. 오로지 프로퍼티가 존재하는지만 판단한다.

interface는 다양한 옵션들을 제공한다.

선택적 프로퍼티

프로퍼티의 존재 여부가 경우에 따라 다를 때 사용한다.

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

읽기전용 프로퍼티

프로퍼티를 읽기 전용으로 만든다. 첫 할당 이후 변경 불가능하다.

interface User{
  readonly name: string;
  readonly age: number;
  address? : string;
}

const user: User = {name: 'Jhon Doe', age: 35};
user.name = 'oh oh'; // 에러 발생

클래스 타입

클래스 타입도 interface로 지정할 수 있다.

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

interface 확장

인터페이스를 확장하여 사용할 수도 있다.

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
profile
FrontEnd Developer

0개의 댓글