본문 바로가기

Frontend Study - 2/Typescript

Typescript : 복습정리 - 2 (함수의 타입, interface, class의 타입지정)

*함수의 타입 표현방법

 

function test(x : string) : number {

}

 

이것을 type alias를 통해 관리할 수 있다. 

 

type testType = (x : string ) => number;

 

같은 의미가 되는 것이다.

사용하려면 함수 표현식으로 사용해야 한다. 

 

type testType = (x : string) => void
let test : testType = function(name) {
	console.log(name)
	}

 

 

타입스크립트로 HTML 변경과 조작 시 주의점.

 

const title = document.querySelector(“#title);

if (title instances Element) {

title.innerHTML = “hello”

}

 

—>> narrowing 해주어야 하는 이유는,

첫번째 줄에서 요소가 없을 경우 null값이 올 수 있기 때문에 타입이 element | null 로 잡혀있기 때문이다. 

 

 

 

class 와 타입스크립트

 

 

class Person {

	name : string;  // 이부분이 다르다. 아래 this.name을 쓰려면 필드값에서 타입을 지정해서 선언 해주어야 한다.
				//자바스크립트에서는 필드값 없어도 사용이 가능하다. 
        constructor() {
        this.name = ‘kim’
        }
}

const me = new Person();

 

 

class Person {

    name : string;  
    constructor( a : string ) { // 파라미터값에 대한 타입지정 방법
    this.name = a
    }

}

const me = new Person(“kim”);

 

리턴값에 대한 타입 지정

class Person {

    name : string;  
    constructor( a : string ) : {} //이런식으로 리턴 값도 지정해 줄 수는 있지만, 인스턴스들은 보통 object형식이기 때문에 굳이 안해주어도 된다. 
    this.name = a
    }

}

const me = new Person(“kim”);

 

class Person {

    name : string;  
    constructor( a : string ) {
    this.name = a
    }

    func( x : string  ) { // 메소드에도 물론 지정 가능하다. 
    console.log(x)
    }

}

const me = new Person(“kim”);
me.func(“kim”)

 

 

 

Object에 타입지정하기 ! interface!

 

type 타입명 = string;

이 때  값이 object의 경우 'type' 대신 'interface'를 써도 된다 !

type과 다르게 등호가 필요없다.

 

interface Square { color : string, width : number }

let figure : Square = {color : “red”, width : 10}

 

 

extends가 가능하다.

 

interface Square {
    color : string,
    width : number,
}

interface Circle extends Square {
    height : number,
}

 

일반 type에서도 intersection을 통해서 유사하게 사용할 수 있다.

 

type Animal = {name : string}

type Cat = {age : number} & Animal

 

interface와 일반 type의 중요한 차이점은. 

interface는 중복선언이 가능하는 것이다. 추가되는 개념이다.

 

interface Student {
	name : string
{

interface Student {
	score : number
}


Student라는 interface안에는, { name : string, score : number} 두 타입이 들어가게 된다. 
extends되는 것.

 

 

type은 중복선언 불가하다. 

 

 

인터페이스를 쓰는 경우 !!

 

위와 같이 interface를 사용했을 경우 중복 선언이 가능하기 때문에, 추후에 타입을 추가 하기가 쉽다.

내가 짠 코드를 다른 사람들이 많이 이용 할 것 같다면, object 타입 지정할 때 interface를 쓰는게 좋다 ! 

 

 

그리고 type과 비교하여 또 다른 차이점이 있따. interface는 중복 속성을 일찍 잡아준다.

interface Student {
	name : string
{

interface Teacher extends Student {
	name : number   //error!
}

 

interface는 선언을 할 때 중복되는 부분을 잡아주는 반면, 

 

Type + & 연산자를 사용하면

 

type Student = {name : string}
type Teacher = {name : string } & Student // no error!

const kc : Teacher  = {name : “강철”}  //error!

 

타입을 만들때  에러를 잡아주는 것이 아니라, 

그 타입을 사용하는 순간 타입 never에러가 나면서 잡아준다. 

 

interface가 먼저 잡아주는 면에서 더 안정적이라고 할 수 있겠다. 

 

type과 interface의 차이점 두가지는

중복선언 가능 여부와, 중복 속성 생성시 error 잡아주는 타이밍의 차이이다.  

 

 

 

참고사이트 

코딩애플 타입스크립트 강의 : https://codingapple.com/