TypeScript 타입 설정

N·2023년 1월 9일

typescript

목록 보기
2/7
  • 타입스크립트는 자바스크립트의 변수, 매개변수, 리턴값에 type을 붙여놓은 것! 주의할 점: 타입을 대문자로 쓰면 안된다!
    tip) type(:뒤에 있는 내용)을 지우면 js 코드가 되도록 만들어보자!
e.g. 
const a: number = 5;
const b: string = 'hello';
const c: boolean = true;
const d: undefined = undefined;
const e: null = null;
const f: symbol = Symbol.for('abc');
const g: bigint = 1000000n;
const f: any = true;

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

//화살표함수 사용하는 방법
const add: (x: number, y: number) => number = (x, y) => x + y;
//or
type Add = (x: number, y: number) => number;
const add: Add = (x, y) => x + y;
//or
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 arr2: number[] = [123, 456]
const arr3: Array<number> = [123, 456] //제네릭
const arr4: [number, number, string] = [123, 456, 'hi']//튜플 -> 길이가 고정된 배열

//type 자리에 고정된 원시값을 넣는 방법
const f: true = true;
const g: 5 = 5;

//advanced
let aa = 123;
aa = 'hello' as unknown as number;

//주의해야 하는 타입 -> never
let arr = []; //-> arr: never[] -> 배열안에 아무것도 넣지 못한다

//따라서 배열을 초기화 할 때는 반드시 타입을 지정해주자!
let arr: string = [];
profile
web

0개의 댓글