본문 바로가기
TypeScript

[TIL] 타입스크립트 - 자료형

by yj.yoon 2023. 9. 11.

흔치 않은 기회!

회사에서 공부하기

 

참고 자료는 https://2woongjae.notion.site/TypeScript-Cookbook-727820ac0d4544498ebe732e940816f4

 

TypeScript Cookbook

A new tool for teams & individuals that blends everyday work apps into one.

2woongjae.notion.site

 

 

~ 위의 문서 읽고 메모하기 ~

 


역사

타입스크립트는 2012년에 나왔다. 17년에는 구글 사내 표준 언어가 되었다.

 

Compiled Language로 TS -> JS 로 컴파일해서 사용한다.

* 자바스크립트는 별도의 컴파일 없이 바로 실행 가능, Interpreted Language

 

자료형

- Primitive Types : 실제 값을 저장하는 자료형

종류는 boolean, number, string, symbol, null, undefined

* symbol : 고유하고 수정불가능한 값으로 만들어준다.

 

- Literal Types : 변수가 아니라 고정된 값으로서 "문자 그대로" 스크립트에 값을 제공하고 타입으로 사용 가능

 

const age = 26;
const name = 'yejin'

age = 27 // false
name = 'Yejin' // false

 

 

- Tuple Types : 배열인데 타입이 한 가지가 아닌 경우, 객체임

 

const person : [string, number] = ['yejin', 26];
const [name, age] = person;

 

 

- Any Types : 아무거나 타입, 이걸 최대한 쓰지 않는 것이 중요

 

 

- Unknown Types : TypeScript 3.0 버전부터 지원. any 보다 Type-safe한 타입

컴파일러가 타입을 추론할 수 있게 타입의 유형을 좁히는 것이 가능하고, 타입을 정해주지 않으면 다른 곳에 할당 및 사용할 수 없다.

 

const unknownStr : unknown = '알 수 없음';

let text : string = unknownStr; // error
text = unknownStr as string // success

if (typeof unknownStr === 'string') {
	text = unknownStr; // success
}

 

 

- Enum Types

1) Numeric enums

 

enum Color1 {Red, Green, Blue}
const c1 : Color1 = Color1.Green;
console.log(c1); // 1

enum Color2 {Red = 1, Green, Blue}
const c2 : Color2 = Color2.Green;
console.log(c2); // 2

enum Color3 {Red = 1, Green = 2, Blue = 4}
const c3 : Color3 = Color3.Green;
console.log(c3); // 3

enum Color4 {Red = 1, Green, Blue}

const colorName: string = Color4[2];
console.log(colorName); // Green

 

 

2) Reverse mappings (omly Numeric)

 

enum EnumAB {
	A,
	B
}

const b = EnumAB.B
const nameOf_B : string = EnumAB[b];

console.log(b, nameOf_B); // 1, 'B'

 

 

- Aliasing Tuple : 튜플 타입에 별칭을 줘서 사용 가능하다. <- 유용해보임!

 

let person: [string, number] = ['yejin', 26];

type personTuple = [string, number];

let another: personTuple = ['jass', 26];

 

 

- Indexable Types

 

interface StringArray {
	[index: number] : string; // number type
}

const str_arr : StringArray = {}; // optional
str_arr[100] = '백';

interface StringDictionary {
	[index: string] : string; // string type
}

const str_arr2 : StringDictionary = {}; // optional
str_arr2.hundred = '백';

interface StringArrayDictionary {
	[index: number] : string;
	[index: string] : string;
}

const sad : StringArrayDictionary = {};
sad[100] = '백';
sad.hudred = '백';

 

 

제너릭

Generic 타입을 쓰지 않으면, T를 추론

Generic 타입을 쓰면, T를 검증

 

// basic
function helloBasic<T>(message: T): T {
	return message;
}

console.log(helloBasic<string>('Mark'));

const age = helloBasic(36); // T를 추론
// helloBasic<number>('36'); (X)

 

 

직접 타이핑하면서 눈에 익히려고 했다.

후루룩 자료 읽기 완료~

내일도 과연 일이 없을 것인가....