Typescript 5분 개요

dd_dev·2022년 10월 3일
0

Typescript 5분 개요

타입 추론 (Types by Inference)

변수를 생성하면서 동시에 특정 값에 할당하는 경우, TypeScript는 그 값을 해당 변수의 타입으로 사용할 것입니다.

타입 정의하기 (Defining Types)

몇몇 디자인 패턴은 자동으로 타입을 제공하기 힘들 수 있는데 (동적 프로그래밍을 사용하고 있을 것이기 때문에) 이러한 경우에 TypeScript는 TypeScript에게 타입이 무엇이 되어야 하는지 명시 가능한 JavaScript 언어의 확장을 지원합니다.

이 객체의 형태를 명시적으로 나타내기 위해서는 interface 로 선언합니다.

interface User {
  name: string;
  id: number;
}
// ---cut---
const user: User = {
  name: "Hayes",
  id: 0,
};

인터페이스는 클래스로도 선언할 수 있습니다.

class UserAccount {
  name: string;
  id: number;
  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}
const user: User = new UserAccount("Murphy", 1);

인터페이스는 함수에서 매개변수와 리턴 값을 명시하는데 사용되기도 합니다.

// ---cut---
function getAdminUser(): User {
  //...
}
function deleteUser(user: User) {
  // ...
}

boolean, bigint, null, number, string, symbol, object와 undefined는 인터페이스에서 사용할 수 있습니다. TypeScript는 몇 가지를 추가해 목록을 확장합니다.

  • any (무엇이든 허용합니다)
  • unknown (이 타입을 사용하는 사람이 타입이 무엇인지 선언했는가를 확인하십시오)
  • never (이 타입은 발생될 수 없습니다)
  • void (undefined를 리턴하거나 리턴 값이 없는 함수).

타입을 구축하기 위한 두 가지 구문이 있다는 것을 꽤 빠르게 알 수 있을 것입니다.: Interfaces and Types - interface를 우선적으로 사용하고 특정 기능이 필요할 때 type을 사용해야 합니다.

타입 구성 (Composing Types)

유니언 (Unions)

타입이 여러 타입 중 하나일 수 있음을 선언하는 방법입니다

type MyBool = true | false;
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;
function getLength(obj: string | string[]) {
  return obj.length;
}
TypePredicate
stringtypeof s === "string"
numbertypeof n === "number"
booleantypeof b === "boolean"
undefinedtypeof undefined === "undefined"
functiontypeof f === "function"
arrayArray.isArray(a)

제네릭 (Generics)

타입에 변수를 제공하는 방법입니다.

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

구조적 타입 시스템 (Structural Type System)

구조적 타입 시스템에서 두 객체가 같은 형태를 가지면 같은 것으로 간주됩니다.

interface Point {
  x: number;
  y: number;
}

function printPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}

// "12, 26"를 출력합니다
const point = { x: 12, y: 26 };
printPoint(point);
profile
developer

0개의 댓글