[Typescript] Basic Types

eunn·2020년 1월 1일
0

Javascript 기본 자료형

Boolean / boolean

let isDone: boolean =  false;
typeof isDone === 'boolean' //true
// Type 'boolean' is assignable to type 'Boolean'.
let isOk: Boolean = true;
// Type 'Boolean' is not assignable to type 'boolean'.
// 'boolean' is a primitive, but 'Boolean' is a wrapper object.
// Prefer using 'boolean' when possible.
let isNotOk: boolean = new Boolean(true);

number

string

null / undefined

  • undefined & null are subtypes of all other types.

  • number 에 null 또는 undefined 를 할당할 수 있다.
  • but, 컴파일 옵션에서 --strictNullChecks 사용하면, null 과 undefined 는 void 나 자기 자신들에게만 할당할 수 있다.
  • null 과 undefined 를 할당할 수 있게 하려면, union type 을 이용해야 한다.
let name: string = null;
let age: number = undefined;
// strictNullChecks => true
// Type 'null' is not assignable to type 'string'.
let name: string = null; (x)
// null => null || void, undefined => undefined || void
// Type 'null' is not assignable to type 'undefined'.
let u: undefined = null; // (x)
let v: void = undefined; // (o)
let union: string | null | undefined = 'str';

symbol (ECMAScript6 에 추가)

  • ECMAScript2015 의 Symbol.

  • primitive 의 값을 담아서 사용.

  • 고유하고 수정불가능한 값으로 만들어준다. (주로 접근을 제어하는 데 쓰는 경우가 많다.)

     let sym = symbol();
     let obj = {
       [sym]: "value"
     };
     console.log(obj[sym]); // "value"

Array: object 형

let list: number[] = [1,2,3];
let list: Array<number> = [4,5,6];

그 외 자료형

any

  • 어떤 타입이어도 상관없다.
  • 컴파일 옵션 중 any를 쓰면 오류가 나도록 하는 옵션이 있다. (nolmplicitAny)

void

  • 타입이 없는 상태
  • 'any' 와 반대
  • 주로 함수의 리턴이 없을 때 사용.
    function returnVoid(message): void {
      console.log(message);
    }
    returnVoid('리턴이 없다');

never

  • 리턴에 주로 사용
  • 주로 3가지 경우에 사용
    // Function returning never must have unreachable end point
    function error(message: string): never {
      throw new Error(message);
    }
    // Inferred return type is never
    function fail() {
      return error("Something failed")
    }
    // Function returning never must have unreachable end poing
    function infiniteLoop(): never {
      while (true) {
      }
    }

enum

enum Color {Red, Green, Blue}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];

tuple: object 형

  • 배열인데 타입이 한 가지가 아닌 경우 사용
    // Declare a tuple type
    let x: [string, number];
    // Initialize it
    x = ['hello', 10]; // OK
    x = [10, 'hello']; // Error
    x[3] = 'world'; // OK, 'string' can be assigned to 'string | number'
    console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'
    x[6] = true // Error, 'boolean' isn't 'string | number'
profile
사람-컴퓨터와 소통하고 싶은 병아리 개발자입니다🐥

0개의 댓글