$ tsc --noEmit
$ npx tsc --init
을 통해 tsconfig.json
파일 생성$ npx tsc --noEmit
명령어를 통해서 터미널에서도 타입검사를 할 수 있다
$ npx tsc
명령어를 통해 ts코드를 js로 변환할 수 있다.const a = (x, y) => x + y
const a: (x: number, y: number) => number = (x, y) => x + y
// type으로 타입을 선언하는 방식 = 타입 애일리어스(type alias)
type A = (x: number, y: number) => number
const a: A = (x, y) => x + y
// interface로 함수 타입 정의
interface A {
(x: number, y: number): number
}
const a: A = (x, y) => x + y
----
const arr: number[] = [1, 2, 3]
const arr: Array<number> = [1, 2, 3]
// 튜플
const arr: [string, number] = ['abc', 123]
const obj: { name: string, age: number } = { name: 'zzz', age: 99 }
as const
를 추가해주면서 타입을 강화할 수 있다const obj = {a: 1, b: 2}
type Key = keyof obj
keyof
를 바로 사용할 경우에는 'obj' refers to a value, but is being used as a type here. Did you mean 'typeof obj'?
경고가 발생한다typeof
를 추가하면서 객체의 key
타입을 추출할 수 있다const obj = {a: 1, b: 2}
type Key = keyof typeof obj
enum EDirection {
Up, // 0부터 순서대로 할당된다
Down,
Left,
Right,
}
EDirection.Down = 123 // [오류] 읽기 전용 속성이므로 'Down'에 할당할 수 없습니다.