TEST - Typescript Object Types

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}
 
// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from.
declare const backpack: Backpack<string>;
 
// object is a string, because we declared it above as the variable part of Backpack.
const object = backpack.get();
 
// Since the backpack variable is a string, you can't pass a number to the add function.
backpack.add(23);

Notice the given argument to createSquare is spelled colour instead of color. In plain JavaScript, this sort of thing fails silently.

You could argue that this program is correctly typed, since the width properties are compatible, there’s no color property present, and the extra colour property is insignificant.

However, TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error:


interface SquareConfig {
  color?: string;
  width?: number;
}
 
function createSquare(config: SquareConfig): { color: string; area: number } {
  return {
    color: config.color || "red",
    area: config.width ? config.width * config.width : 20,
  };
}
 
let mySquare = createSquare({ colour: "red", width: 100 });

다음 내용이 궁금하다면?

또는

이미 회원이신가요?

2024년 2월 7일 오전 9:55

댓글 0

    함께 읽은 게시물

    어려움을 극복하는 힘

    ... 더 보기

    DDD와 AI

    ... 더 보기

    TypeScript 배우기 좋은 오픈소스 프로젝트 모음

    타입스크립트 공부용으로 참고할 수 있는 오픈소스 프로젝트들입니다. HackerNews 유저들의 추천에 기반하여 작성되었습니다. - Excalidraw(오픈소스 가상 칠판 협업도구) https://github.com/excalidraw/excalidraw - Cal.com(오픈소스 캘린더 협업 도구, 오픈소스 Calendly 대체제) https://github.com/calcom/cal.com - Supabase(오픈소스 Firebase 대체제) https://github.com/supabase/supabase... 더 보기

    사용자가 공유한 콘텐츠

    -

    사용자가 공유한 콘텐츠

     • 

    저장 90 • 조회 3,782