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

    함께 읽은 게시물

    개발자는 개발만 잘하면 될까

    최근에 친구가 추천해준 데일 카네기의 인간관계론을 읽던 중 고액 연봉을 받는 엔지니어들의 특징에 대한 흥미로운 내용이 있었다.

    ... 더 보기

     • 

    저장 14 • 조회 2,617


    괴물은 하루아침에 태어나지 않는다

    큰 것을 하는 것보다 매일 작은 것을 완벽하게 해내는 노력이 더 중요하다. 내가 성격 장애의 하나인 자기애성 성격장애자(NPD, Narcissistic Personality Disorder)를 만나면서 느낀 것은, 처음에는 그런 사람도 "정상인"처럼 느껴진다는 것이었다. 다만 그의 미친짓은 내가 매일매일 "사소한" 사건들로 상대방에게 익숙해졌을 때 발생한다.

    ... 더 보기

    어제 AI 시대의 개발자 토론회에서 내가 대 AI 시대에는 버전관리 시스템이 필요없을 수도 있다고 생각해야한다는 말을 했는데, 그정도로 파격적인 생각을 해야한다는 이야기긴했지만, 진짜 그럴까?를 다시 한 번 생각해봤다.


    우선 버전관리 시스템의 목적은 크게 다음 세 가지다.


    ... 더 보기

    조회 1,488


    스트레스를 잘 관리하면서 건강하게 살아가고 싶다면, 우선 살아있는 한 우리가 해야 할 일들은 영원히 없어지지 않을 것이므로, 해야 할 일을 100% 해내면서 할 일 목록을 완전히 없애는 데 많은 노력을 들이기보다는 70% 정도만 해내도 만족할 필요가 있다.

    ... 더 보기

    [박진영의 사회심리학]스스로 만들어 내는 스트레스

    m.dongascience.com

    [박진영의 사회심리학]스스로 만들어 내는 스트레스


    리트코드 102. Binary Tree Level Order Traver

    ... 더 보기

    Binary Tree Level Order Traversal | 알고달레

    알고달레

    Binary Tree Level Order Traversal | 알고달레