ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Exact Optional Property Types
    프로그래밍/typescript 2022. 4. 20. 20:52

    초기 TypeScript에서 optional property에 undefined 타입이 자동으로 지정이 되었습니다.

    이러한 방식은 JavaScript 런타임 시, 값이 objct에 property가 실제로 존재하는지 아닌지 여부에 따라 error가 발생할 수 있습니다.

    interface Person {
      name: string;
      age?: number;
    }
    
    const p: Person = {
      name: "Daniel",
      age: undefined, // This is okay by default.
    };
    

    TypeScript 4.4부터 새로운 플래그인 exactOptionalPropertyTypes 는 optional property type을 쓰여있는 그대로 사용합니다.

    // With 'exactOptionalPropertyTypes' on:
    const p: Person = {
    Type '{ name: string; age: undefined; }' is not assignable to type 'Person' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
      Types of property 'age' are incompatible.
        Type 'undefined' is not assignable to type 'number'.
      name: "Daniel",
      age: undefined, // Error! undefined isn't a number
    };
    

     

    *참조

    https://www.typescriptlang.org/docs/handbook/intro.html

Designed by Tistory.