[TypeScript] 기본 타입

hyo·2023년 1월 23일
0

TypeScript

목록 보기
2/6
post-thumbnail

Typescript 기본 타입

String

아래와 같이 : 으로 타입을 정의하는 방식을 타입표기(Type Annotation) 이라고 한다.

let str: string = 'a';

Number

let n: number = 123;

Boolean

let isClick: boolean = false;

Array

let arr: number[] = [1,2,3];
let arr2: string[] = ['a','b'];
  1. 제네릭 표기법
let arr: Array<number> = [1,2,3,4,5];
let arr2: Array<string> = ['a','b'];

Tuple

Tuple은 배열의 길이가 고정되고 각 요소의 타입이 지정되어 있는 배열 형식을 말한다.

let arr: [number, number] = [1,2];
let arr2: [number, string] = [1,'a'];

let arr3: [string,number] = ['a','b'] -> Error // 1번째 인자타입이 number가 아니기떄문에!
let arr4: [number,number] = [1,2,3] -> Error // 타입표기할때 인덱스 1까지의 길이를 고정 시켰는데 인덱스 2까지의 배열을 할당했기때문에

Enum

enum A{
  a,
  b,
  c,
}

let hyo: A = A.a;
console.log(hyo) -> 0
let hyo2: A = A[1];
console.log(hyo2) -> b
  
enum B{
  a = 2,
  b,
  c,
}
  
let hyo3: B = B[2];
console.log(hyo3) -> a
let hyo4: B = B[4];
console.log(hyo4) -> c // 위의 enum B 에서 a의 인덱스를 2로 default 값을 주고 시작해서 B[4]는 c 이다.
  

Any

모든 타입에 대해서 허용한다는 의미를 갖고 있다.
any 만 쓴다면 typescript 를 쓰는 의미는 없다.

let a: any = 'hhhh';
let b: any = 12345;
let c: any = [1,2,3,'a','b'];

Void

변수에는 undefined , null 만 할당하고, 함수에는 반환 값을 설정할 수 없는 타입!

let a: void = undefined;
let b: void = null;

function A(): void {
  console.log('hello');
}

Never

함수의 끝에 절대 도달하지 않는다는 의미를 가진 타입이다.

function no(): never {
  while() {
  
  }
}
profile
개발 재밌다

0개의 댓글