Type predicate

readonly

ν•΄λ‹Ή λ°°μ—΄, 객체λ₯Ό μˆ˜μ •ν•  수 μ—†κ³  였직 읽을 수만 있게 함.

  • 배열은 ν‘œν˜„ 방법이 string[], Array<string> 2가지 μ΄μ§€λ§Œ, readonlyλ₯Ό μ‚¬μš©ν•  λ•ŒλŠ” string[] ν‘œν˜„μ‹λ§Œ κ°€λŠ₯ν•˜λ‹€.

function printArray(fruits: readonly string[]) {}

| (Union Type)

a λ˜λŠ” b λ˜λŠ” c λ˜λŠ” dκ°€ 올 수 μžˆλ‹€λŠ” 뜻.

type Direction = 'left' | 'right' | 'up' | 'down';

& (Intersection type)

λͺ¨λ“  것을 λ‹€ ν•©ν•œ 의미둜 μ‚¬μš© a도 b도 c도 d도 λ‹€ μžˆμ–΄μ•Ό ν•œλ‹€λŠ”

type Student = {
  name: string;
  score: number;
};

type Worker = {
  empolyeeId: number;
  work: () => void;
};

function internWork(person: Student & Worker) {
  console.log(person.name, person.empolyeeId, person.work());
}

in

μš°ν•­μ— μžˆλŠ” νƒ€μž…μ˜ 속성을 가지고 μžˆλŠ”μ§€ 확인

type SuccessState = {
  response: {
    body: string;
  };
};
type FailState = {
  reason: string;
};
type LoginState = SuccessState | FailState;


function printLoginState(state: LoginState) {
  if ('response' in state) {
    console.log(`πŸŽ‰ ${state.response.body}`);
  } else {
    console.log(`😭 ${state.reason}`);
  }
}

as (Type Assertion)

νƒ€μž…μ„ λͺ…μ‹œμ μœΌλ‘œ 지정해 쀌

function jsStrFunc(): any {
    return 2;
}
const result = jsStrFunc();
console.log((result as string).length);
console.log((<string>result).length);

!

μ ˆλŒ€μ μœΌλ‘œ 값이 μžˆμŒμ„ ν™•μ‹ ν•  λ•Œ ν‘œν˜„

function findNumbers(): number[] | undefined {
    return undefined;
  }
  const numbers = findNumbers()!;
  // or
  numbers!.push(2);

is

Aκ°€ Bνƒ€μž…μΈμ§€ μ•„λ‹Œμ§€ 확인

A is B // true or false

Last updated

Was this helpful?