[TypeScript] Type Aliases and Interface, Literal Types (as const)

수민🐣·2022년 11월 9일
0

TypeScript

목록 보기
7/16

Type Aliases

새로운 타입을 내가 정의할 수 있다

type Text = string;
type Num = number;
const name:Text = 'sumin';
const address:Text = 'korea';

type Student = {
	name: string;
	age: number;
};
const student:Student = {
	name: 'sumin',
	age: 12,
};

type Point = {
	x:number,
	y:number
};
const startPoint:Point = {x:1, y:1};
const endPoint:Point = {x:10 y:15};
// 정의한 데이터를 꼭 써줘야함 안그러면 오류 

Interface

객체의 타입을 지정할 수 있는 방법

interface Point {
	x:number,
	y:number
};

const startPoint:Point = {x:1, y:1};

const endPoint:Point = {x:10 y:15};

Interface vs Type

기능상에 차이는 거의 없다

  • 기존에 작성되어 있는 프로젝트의 경우: 기존 컨벤션을 따른다.
  • 선택권이 있는 경우:
    • Interface는 Object의 추상을 표현하고 싶을 때
      • Class에서 이 Interface를 구현하고 싶다는 경우
      • Object를 표현할 때 ‘이 객체는 이런 변수를 가지고 있고, 이런 동작을 할 수 있어’ 라고 말하고 싶은 경우
    • 그 외의 경우 Type을 사용
      • e.g., React Props, React State, 변수만 있는 Object

String Literal Types

타입을 문자열로 정의

범용적인 string, number 타입이 아닌 정확한 형태의 값을 타입으로 지정 가능

type Name = "name";
let suminName: Name;
suminName = 'name'; 
// 어떠한 문자열을 넣어서는 안됨 
// 정의된 'name'만 가능

type JSON = 'json';
const json: JSON = 'json';
let age:number = 1;
age = 5; // OK

// -----

let age:3 = 3;
age = 3; // OK
age = 5; // Error!


let name:string = "yeonuk";
name = "yeonwook" // OK

// ----

let name:"yeonuk" = "yeonuk";
name = "yeonuk" // OK
name = "yeonwook" // Error!

대부분은 literal type으로 추론

const age = 1;
const name = "yeonuk"

as const - Object나 Array Literal Types

  • Object나 Array 내부의 프로퍼티들의 값을 literal처럼 정확히 지정할 때 사용
  • read only 수정 x
  • theme 할 때 많이 사용 명확하게 이 색이구나를 알 수 있도록!
const numbers = [1,2,3] // number[]
const numbers = [1,2,3] as const // [1,2,3]

const obj = {x:1, y:2} // {x:number, y:number}
const obj = {x:1, y:2} as const // {x:1, y:2}

0개의 댓글