코드베이스를 향상시키는 5가지 TypeScript 기능
이 게시물에서는 코드베이스를 향상시킬 다섯 가지 유형 스크립트 기능에 대해 이야기하고 싶습니다.
내용의 테이블
1. 무효 합체
Let's consider the following example.
function getNumberOrDefault(value?: number) {
return value || 22;
}
In the mentioned example, we would like to return a default value, if the provided value is undefined. However, this code has a severe pitfall — javascript treats 0
as a falsy
value.
console.log(getNumberOrDefault(10)) // Output 10
console.log(getNumberOrDefault(0)) // Output 22
Returning 22
is probably, not something we expect this function to do. Thanks to the nullish coalescing we don't need to refactor the code and add check for 0
, instead we can use a shorthand syntax with ??
.
function getNumberOrDefaultTs(value?: number) {
return value ?? 22;
}
console.log(getNumberOrDefault(10)) // Output 10
console.log(getNumberOrDefault(0)) // Output 0
2. 유형 가드
Let's imagine we have two types, Truck
and F1
, which extend the same interface Car
. Although they share some common properties, they also possess a set of unique attributes like load
and acceleration
respectively.
interface Car {
model: string;
}
interface Truck extends Car {
load: number;
}
interface F1 extends Car {
acceleration: number;
}
function scanCar(car: Truck | F1) {
...some code
}
Also, we have a function scanCar
which accepts either a Truck
or a F1
and performs some type-specific actions.
Type guard is a great way to let typescript know with which type we are currently dealing.
function carIsTruck(car: Truck | F1): car is Truck {
return 'load' in car;
}
function scanCar(car: Truck | F1) {
if(carIsTruck(car)) {
// Only truck properties will be suggested
console.log(`Truck has a load of ${car.load}`)
} else {
// Only F1 properties will be suggested
console.log(`F1 has acceleration of ${car.acceleration}`)
}
}
Type guard is a function that returns a boolean, which is often used as part of the conditional statement, to let typescript know which type is assumed in the current if block.
3. 개체 키 열거
There are some cases when we want to enforce object keys being certain values only. And here is how we can achieve it using enum
and Record
.
enum Size {
M,
L,
XL
}
function getPlainTextSizes(): Record<Size, string> {
return {
[Size.M]: "medium",
[Size.L]: "large",
[Size.XL]: "extra large",
10: "small", // error
"size": "xs" // error
}
}
Record
is a generic type util, which allows defining types for key-value maps.
4. 일반 인터페이스
interface Item<T> {
id: number,
value: T,
}
interface Post {
title: string;
}
const item1: Item<number> = { id: 1, value: 10 }
const item2: Item<Post> = { id: 1, value: { title: "Post name" } }
Generics in typescript significantly improve code reusability.
5. 일반 함수 매개변수 유형
interface Book {
id: number;
author: string;
}
interface Recipe {
id: number;
cookingTime: number;
}
function mapById<T extends { id: number }>(array: T[]): {[key: number]: T} {
return array.reduce((map, item) => ({ ...map, [item.id]: item }), {})
}
const books: Book[] = [{ id: 1, author: "A" }];
const recipies: Recipe[] = [{ id: 1, cookingTime: 10 }];
mapById(books);
mapById(recipies);
It's often the case that we have util functions which require only some field from the interface. In the example above you can see a function which takes an array as input and returns values mapped by id. The only important thing is that the items of the array have an id
. When you pass a parameter to the function typescript will:
- Infere the type of the provided parameter
- Check if the parameter matches specified condition (must have
id
of type number) So now you are save to use this helper for various interfaces.
요약
보시다시피 typescript는 유형 안전성을 희생하지 않고 재사용 가능하고 유연한 코드를 작성할 수 있는 많은 도구를 제공합니다.
읽어 주셔서 감사합니다! 이 게시물은 새로운 형식의 실험입니다. 흥미롭고 도움이 되셨다면 알려주세요. 웹 개발에 대한 더 멋진 정보와 소문을 퍼뜨리는 데 도움을 주세요! 🚀
Reference
이 문제에 관하여(코드베이스를 향상시키는 5가지 TypeScript 기능), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/glebirovich/5-typescript-features-that-will-improve-your-codebase-hok텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)