TypeScript의 Tips 세트

29747 단어 TypeScripttech
이 글은 TypeScript Advent Calendar 2020 17일째다.
이번에는 Type Script의 Tips를 몇 개!
기본이 많은 편이라 평소 타입 스크립트를 열심히 쓰는 사람에게는 이미 알고 있는 게 많을 수도 있다.다만, 자각하지 못하면 잘 쓰지 않고, 타입 스크립트 경험이 없는 사람에게도 신선한 게 있지 않을까요?그래서 썼어요.

keyof


대상 키를 union형으로 변환하기
type Post = {
  id: number;
  title: string;
  content: string;
};

type PostKey = keyof Post;
// type PostKey = "id" | "title" | "content"
사용 시 이런 느낌인가요?
const sortBy = <T extends object, K extends keyof T>(
  objects: T[],
  key: K
): T[] => {
  return objects.sort((a, b) => a[`${key}`] - b[`${key}`]);
};

const posts = [
  { id: 1, title: 'test1' },
  { id: 3, title: 'test3' },
  { id: 2, title: 'test2' },
];

console.log(sortBy(posts, 'id'));
// [
//   { id: 1, title: 'test1' },
//   { id: 2, title: 'test2' },
//   { id: 3, title: 'test3' }
// ]

console.log(sortBy(posts, 'name'));
// Argument of type '"name"' is not assignable to parameter of type '"id" | "title"'

lookup


예를 들어, API의 반환 값이 다음 유형인 경우
(GiitHub API 참조)
type 속성을 꺼낼 수 있는 유형은 다음과 같습니다
type Response = {
  repository: {
    id: string;
    homepageUrl: string;
    issues: {
      edges: {
        node: {
          author: {
            url: string;
          };
          body: string;
        };
      };
      totalCount: number;
    }[];
  };
};

type Issues = Response['repository']['issues'];
// type Issues = {
//     edges: {
//         node: {
//             author: {
//                 url: string;
//             };
//             body: string;
//         };
//     };
//     totalCount: number;
// }[]

type IssueTotalCount = Issues[0]['totalCount'];
// type IssueTotalCount = number

utility


Partial


모든 필드가 Optional
type Post = {
  id: number;
  title: string;
};
type PartialPost = Partial<Post>;
// type PartialPost = {
//     id?: number;
//     title?: string;
// }
const post1: PartialPost = { id: 1 };

Required


모든 필드는 필수입니다.
type Post = {
  id: number;
  title: string;
  userId?: number;
};
type RequiredPost = Required<Post>;
// type RequiredPost = {
//     id: number;
//     title: string;
//     userId: number;
// }

Readonly


모든 필드가 읽기 전용입니다.
type Post = {
  id: number;
  title: string;
};

type ReadonlyPost = Readonly<Post>;
// type ReadonlyPost = {
//   readonly id: number;
//   readonly title: string;
// };
const readonlyPost: ReadonlyPost = { id: 1, title: 'readonly' };
readonlyPost.title = 'update';
// Cannot assign to 'title' because it is a read-only property.

Pick


지정한 키만 꺼내기
type Post = {
  id: number;
  title: string;
};

type PickPost = Pick<Post, 'id'>;
// type PickPost = {
//     id: number;
// }

Omit


지정한 키 제외
type Post = {
  id: number;
  title: string;
  content: string;
};

type OmitPost = Omit<Post, 'id' | 'title'>;
// type OmitPost = {
//     content: string;
// }

Exclude


유니언형에서 제외
type RGB = 'red' | 'green' | 'blue';
type RG = Exclude<RGB, 'blue'>;
// type RG = "red" | "green"

ReturnType


함수 반환 값의 유형을 얻을 수 있습니다
const add = (a: number, b: number): number => {
  return a + b;
};
type AddReturnType = ReturnType<typeof add>;
// type AddReturnType = number
다른 것도 많아요.
utility-types

as const


발표as const할 때 이후 형추론으로 인해 대형을 확대하지 않고readonly가 되었다.
let constPost = { id: 1, title: 'title', content: 'content' } as const;
// let constPost: {
//     readonly id: 1;
//     readonly title: "title";
//     readonly content: "content";
// }

Enum은 사용하지 말아야 할 말이에요.


자주 듣지만 엔음은 추천하지 않아요.
안녕, Type Script enum
Tree-shoking의 관점에서 Type Script를 사용하지 않는 enum의 이유를 설명합니다.
엔음의 대체품으로 다음과 같은 느낌이 있어요.
const Country = {
  JAPAN: 'JAPAN',
  USA: 'USA',
  CHINA: 'CHINA',
} as const;

type Country = typeof Country[keyof typeof Country];

조개


만약 비어 있지 않은 것이 확실하다면, 비어 있지 않은 것을 명확하게 지정할 수 있다
document.getElementById("test").innerHTML
// Object is possibly 'null'.
document.getElementById("test")!.innerHTML
// コンパイルエラーなし

let text;
if (...) {
  text = 'text1'
} else if (...) {
  text = 'text2'
}
text.substr(...)
// let text: string | undefined
// Object is possibly 'undefined'
text!.substr(...)
//コンパイルエラーなし
기본적으로 추천하지 않기 때문에 사용하는 것이 좋다?
document.getElementById('test')?.innerHTML;

Template Literal Types


4.1 눈동자 기능Template Literal Types
형식 정의에서template literal을 사용할 수 있습니다.
먼저 template literal 을 설명하면 문자열에 변수를 삽입하는 문법
const world = 'World';

console.log(`Hello ${world}!`);
// 'Hello World!';
type DataFormat = 'HTML' | 'JSON' | 'XML';
type Parser = `parse${DataFormat}`;
// type Parser = "parseHTML" | "parseJSON" | "parseXML"
type parser1: Parser = 'parseHTML'
type parser2: Parser = 'parseHogehoge'
// Type '"parseHogehoge"' is not assignable to type '"parseHTML" | "parseJSON" | "parseXML"'.

type Satoshi = `Satoshi${string}`;
const satoshi1: Satoshi = 'Satoshi';
const satoshi2: Satoshi = 'Satoshi Tanaka';
const notSatoshi: Satoshi = 'Taro Tanaka';
// Type '"Taro Tanaka"' is not assignable to type '`Satoshi${string}`'.

Template Literal Types가 있으면 SQL에도 모형을 추가할 수 있습니다
ts-sql

최후


타입 스크립트는 유연하게 틀을 정의할 수 있어 기쁘지만, 평소 주의하지 않으면 직감이 둔해지기 때문에 적극적으로 사용해야 한다.

좋은 웹페이지 즐겨찾기