Array

  • array 는 객체.
  • 사용방법
    • Array<타입>
    • 타입[]
let list: number[] = [1, 2, 3];

let list: Array<number> = [1, 2, 3];

 

 

Tuple

  • 배열인데 타입이 한가지가 아닌 경우
  • tuple은 객체.
  • 꺼내 사용할때 주의가 필요하다.
    • 배열을 Destructuting 하면 타입이 제대로 얻어짐
let x: [string, number]; // Declare a tuple type
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error

x[3] = "world"; // Type '"world"' is not assignable to type 'undefined'.

const person: [string, number] = ["mark", 35];

const [first, second, third] = person; // Error

 

 

Any

  • 어떤 타입이어도 상관없는 타입이다.
  • 핵심은 any를 최대한 쓰지 않는 것. 왜냐면 컴파일 타임에 타입 체크가 정상적으로 이뤄지지 않기 때문.
  • 그래서 컴파일 옵션 중에는 any를 써야하는데 쓰지 않으면 오류를 뱉도록 하는 옵션도 있다고 한다.
    • noImplicitAny
function returnAny(message): any {
    console.log(message);
}

returnVoid('리턴은 아무거나');
  • any 는 계속해서 개체를 통해 전파된다.
  • 결국, 모든 편의는 타입 안전성을 잃는 대가로 온다는 것을 기억해야 한다.
  • 타입 안전성은 TypeScript 를 사용하는 주요 동기 중 하나이며 필요하지 않은 경우에는 any 를 사용하지 않도록 해야 한다.
let looselyTyped: any = {};

let d = looselyTyped.a.b.c.d;
//  ^ = let d: any

 

 

 

Unknown

  • 응용 프로그램을 작성할 때 모르는 변수의 타입을 묘사해야 할 수도 있다.
  • 이 경우, 컴파일러와 미래의 코드를 읽는 사람에게 이 변수가 무엇이든 될 수 있음을 알려주는 타입을 제공하기를 원하므로 unknown 타입을 제공.
  • typeof 검사, 비교 검사 또는 고급 타입 가드를 수행하여 보다 구체적인 변수로 좁힐 수 있음.
declare const maybe: unknown;
// 'maybe' could be a string, object, boolean, undefined, or other types
const aNumber: number = maybe; // Type 'unknown' is not assignable to type 'number'.

if (maybe === true) {
  // TypeScript knows that maybe is a boolean now
  const aBoolean: boolean = maybe;
  // So, it cannot be a string
  const aString: string = maybe; // Type 'boolean' is not assignable to type 'string'.
}

if (typeof maybe === "string") {
  // TypeScript knows that maybe is a string
  const aString: string = maybe;
  // So, it cannot be a boolean
  const aBoolean: boolean = maybe; // Type 'string' is not assignable to type 'boolean'.
}

 

 

Never

  • 리턴에 사용된다.
  • 리턴에 사용되는 경우, 아래 3가지 정도의 경우가 대부분
// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

// Inferred return type is never
function fail() {
    return error("Something failed");
}

// Function returning never must have unreachable end point
function infiniteLoop(): never {
    while (true) {
    }

 

  • never 타입은 모든 타입의 subtype 이며, 모든 타입에 할당 할 수 있다.
  • 하지만, never 에는 그 어떤 것도 할당할 수 없다.
  • any 조차도 never 에게 할당 할 수 없다.
  • 잘못된 타입을 넣는 실수를 막고자 할 때 사용하기도 한다.
let a: string = 'hello';

if (typeof a !== 'string') {
    let b: never = a;
}

 

 

 

Void

  • 어떤 타입도 가지지 않는 빈 상태를 의미.
  • 값은 없고 타입만 있다.
  • 일반적으로 값을 반환하지 않는 함수의 리턴 타입으로 사용한다.
    그 외에는 사용할 일이 거의 없다.
  • 할당이 가능한 값은 undefined.
function returnVoid(message): void {
    console.log(message);
}

returnVoid('리턴이 없다');

let unusable: void = undefined;

'Typescript 내용 정리' 카테고리의 다른 글

타입 호환성(type compatibility)  (0) 2023.04.10
Basic Type(1)  (0) 2023.04.01

+ Recent posts