타입스크립트/타입

타입 추론

webmaster 2022. 10. 17. 21:48
728x90

타입 추론 기본

타입 추론이란 타입 스크립트가 코드를 해석해 나가는 동작을 의미한다.

var a = 'abc'; //값을 어떤것으로 설정하냐에 따라 타입이 변경된다.

function getB(b = 10) { //b값을 넘기지 않으면, 10이 할당 되며, 타입이 number로 추론된다
    var c = 'hi' //c 타입은 string으로 타입추론이 일어났다
    return b + c; //숫자 + 문자 = 문
}

인터페이스와 제네릭을 이용한 타입 추론 방식

//타입 추론 기본 2
interface Dropdown<T> {
    value: T;
    title: string;
}

var shoppingItem: Dropdown<string> = { //제네릭의 값을 타입스크립트가 추론한다
    value: "abc",
    title: 'hello',
}
  • 인터페이스의 제네릭 타입을 선언 후, 이를 생성할 때, 타입 스크립트가 제네릭 타입의 타입을 추론한다.

복잡한 구조에서의 타입 추론 방식

//타입 추론 기본3
interface Dropdown<T> {
    value: T;
    title: string;
}

interface DetailedDropdown<V> extends Dropdown<V> {
    //Dropdown을 value 또한 V타입, DetailedDropdown의 tag 역시 V 타입이 된다
    description: string;
    tag: V;
}

var detailedItem: DetailedDropdown<number> = {
    title: 'abc',
    description: 'ab',
    value: 1,
    tag: 2
}
  • 2개의 인터페이스를 각각 제네릭으로 선언한다.
  • 선언한 인터페이스 중 하나를 상속받는 DetailedDropdown에서 Dropdown을 상속받으며, 이때 제네릭 타입을 지정해 줄 수 있다.
    • 현재는 입력받는 제네릭 타입인 V로 부모 자식의 제네릭 타입이 같다.

가장 적절한 타입

만약 배열에 들어가는 타입이 서로 다 다르다면? 어떻게 추론될까?

//Best Common Type : TypeScript가 비슷한 타입을 어떤 타입으로 추론할 지 정해주는 알고리즘(가장 근접한 타입을 찾아간다, Union)
var arr1 = [1, 2, true] //number | boolean
var arr2 = [1, 2, true, true, 'a']
  • 타입이 여러 개 추론되면, |으로 묶어서 유니온 연산을 한다.
  • 여러 타입중 어떤 타입일지 적절하게 선택해 주는 것을 Best Common Type이라고 한다

Typescript Language Server 

Typescript Language Server 가 VS 코드 내부적으로 돌고, 있기 때문에 타입 추론이 가능하며, 아래 자세한 링크가 나와 있다.

https://code.visualstudio.com/docs/languages/typescript#_code-suggestions

 

TypeScript Programming with Visual Studio Code

Get the best out editing TypeScript with Visual Studio Code.

code.visualstudio.com

https://code.visualstudio.com/api/language-extensions/language-server-extension-guide

 

Language Server Extension Guide

Learn how to create Language Servers to provide rich language features in Visual Studio Code.

code.visualstudio.com

https://langserver.org/

 

Langserver.org

The solution: lang servers and clients

langserver.org

https://learn.microsoft.com/ko-kr/visualstudio/extensibility/language-server-protocol?view=vs-2019 

 

언어 서버 프로토콜 개요 - Visual Studio (Windows)

언어 서버 프로토콜이 다양한 도구에 언어 기능을 노출하는 데 유용한 프레임워크를 제공하는 방법에 대해 알아봅니다.

learn.microsoft.com

 

728x90

'타입스크립트 > 타입' 카테고리의 다른 글

타입 모듈화  (0) 2022.10.17
타입 호환  (0) 2022.10.17
타입 가드  (0) 2022.10.17
타입 단언  (0) 2022.10.17