TypeScript - 시작하기

프동프동·2022년 7월 31일
0

TypeScript

목록 보기
1/1
post-thumbnail

VS code

npm 환경 구성

npm i -y

tsc 환경 구성

npx tsc --init

tsconfig.json 수정하여 Javascript, Typescript 동시에 사용하기

...
/* JavaScript Support */
"allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1,
...

tsconfig.json 수정하여 브라우저에 맞는 버전으로 변경하기

...
/* Language and Environment */
"target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve",
...

변수

변수

const a: number = 5;
const b: string = 'name';
const c: boolean = true;
const d: undefined = undefined;
const e: null = null;
const f : any = true;
const g: true = true;
const h: 5 = 5;

함수

일반 함수

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

화살표 함수

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

cosnt add = (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 };

as const

사용자는 0, 1, 2, 3이라는 타입을 명시적으로 넣어줬지만 타입스크립트가 number로 변환함

사용자가 임의로 설정

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

as const를 사용한 설정

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

배열

const arr: string[] = ['123', '456'];
const arr2: number[] = [123, 456];

제네릭 형태로 사용

const arr3: Array<number> = [123, 456];

Tuple 형태로 사용

const arr4: [number, number, string] = [123, 456, 'hello'];

Enum

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

const a = EDirection.Up;
const c = EDirection.Left;

잉여 속성 검사

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

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

const obj1: A = obj;
profile
좋은 개발자가 되고싶은

0개의 댓글