[TypeScript] 함수와 객체의 타입 (Type of Object and Function)

suno·2023년 1월 16일
post-thumbnail

Variables

Type Annotation (타입 애너테이션)

애너테이션은 주석과 같이 프로그램 실행에 영향을 미치지 않으면서 유용한 정보를 제공하는 것을 말한다.

타입스크립트에서 타입을 표시하는 것은 Type Annotation이다.

Type Inference (타입 추론)

변수의 타입을 추론할 수 있는 경우에는 타입을 명시하지 않아도 된다.

let name = ‘suno’;
위와 같이 작성하면 추론을 통해 name: string이라고 타입이 명시된다.

Any

any 타입은 모든 타입이 가능하다.

let thing: any = 'hello';
thing = 1;
thing = false;
thing();
thing.toUpperCase();

Function Parameter

인자의 타입과 기본값을 설정할 수 있고, return 값의 타입을 명시할 수 있다.

function greet2(person: string = 'stranger'): string {
  return `Hi there, ${person}`;
}

Object

Object 또한 프로퍼티의 타입을 명시할 수 있다.

let coordinate: { x: number; y: number }

Alias

object 타입에 별칭을 지정할 수 있다.

type Point = {
  x: number;
  y: number;
};

let point: Point = { x: 1, y: 2 };

Optional Property

선택적 프로퍼티를 명시할 수 있다.

type Point = {
  x: number;
  y: number;
  z?: number; // optional property
};

const myPoint: Point = { x: 1, y: 2 };
const myPoint2: Point = { x: 1, y: 2, z: 3 };

Read-only Property

readonly 프로퍼티는 수정할 수 없다.

단, 참조된 object 타입의 프로퍼티는 수정이 가능하다.

type User = {
  readonly id: number;
  username: string;
};

Intersection Type

서로 다른 Type을 교차할 수 있다.

type Circle = {
  radius: number;
};

type Colorful = {
  color: string;
};

type ColorfulCicle = Circle & Colorful;

const happyFace: ColorfulCicle = {
  radius: 10,
  color: 'yello',
};
profile
Software Engineer 🍊

0개의 댓글