판다꼬마 2022. 8. 17. 23:48
728x90

TS는 간단히 말해

JavaScript에 변수, 매개변수, 리턴 값에 타입을 붙인 것이 TypeScript이다.

 

 

const a: string = "5";
const b: number = 5;
const c: boolean = true;
const d: undefined = undefined;
const e: null = null;

변수는 소문자로 시작해야 한다. Number =>  X

 

 

any

const f: any ="123";
const f: any =true;

any는 모든 타입이 다 된다.

 


 

함수

function add(x: number, y: number): number {
    return x + y;
}

매개변수 바로 뒤에 리턴 값 타입을 적어주면 된다.

 

화살표 함수

const add: (x: number, y:number) => number = (x,y) => x+y;

이렇게 적을 수도 있고 타입을 따로 뺄 수도 있다.

type Add= (x:number, y:number)=> number;
const add: Add= (x,y) => x + y;

 

interface

interface Add {
    (x: number, y: number): number;
}

const add: Add = (x, y) => x + y;

이렇게도 적을 수 있다.


객체

const obj: { lat: number; lon: number } = { lat: 37.5, lon: 127.5 };

 

배열

const arr: string[] = ["123", "456"];
const arr: Array<number> = [123, 456];

이렇게 작성할 수도 있다.

 

 

튜플

const arr3: [number, number, string] = [123, 456, "hello"];

길이가 고정된 배열

 

배열 선언

const array: string[] =[];
array.push('hello');

이렇게 배열을 선언 할때 타입도 같이 작성을 해야 나중에 배열에 값을 넣을 때 오류가 나지 않는다.


 ! 대신 if

const head = document.querySelector('#head')!;
console.log(head);

const head = document.querySelector('#head');
if (head) {
  console.log(head);
}

 

 

템블릿 리터럴 타입

type World = "world" | "hell";

// type Greeting = "hello world"
type Greeting = `hello ${World}`;

이렇게 자동완성으로 추천도 해준다.

 

 

 

배열

let arr: string[] = [];
let arr2: Array<string> = [];
function rest(...args: string[]) {
    console.log(a, args); //1, [2,3]
}

 

 

enum

const enum EDirection {
    Up,
    Down,
    Left,
    Right,
  }

Up Down Left Right 순서대로 0 , 1 , 2 , 3이 된다.

만약 Up이 3이라고 지정을 하면 순서대로 3, 4, 5, 6이 된다.

 

이렇게 사용하기 싫으면

  const ODirection = {
    Up: 0,
    Down: 1,
    Left: 2,
    Right: 3,
  } as const;

이렇게 작성하면 된다.

as const의 의미는 타입 검사를 더 세게 한다는 뜻!

 

 

const obj ={ a:'123', b:'hello', c: 'world'} as const;
type Key=typeof obj[keyof typeof obj];

값을 타입으로 쓰고 싶을때 => typeof

이제 키들만 뽑고 싶다  => keyof

 

 

 

객체 타이핑

type A = { a: string };
const a: A = { a: 'hello' };

interface B { a: string }
const b: B = { a: 'hello' };

 

extends

interface A {
    breath: true;
}
interface B extends A {
    breed: true;
}

const b: B = { breath: true, breed: true };

이렇게 받을 수도 있다.

 

interface끼리는 합체

interface A { a: string }
interface A { b: string }
const obj1: A = { a: 'hello', b: 'world' }

type B = { a: string }
type B = { b: string }
const obj2: B = { a: 'hello', b: 'world' }

 

728x90