상세 컨텐츠

본문 제목

[번역] What are Type Predicates in Typescript?

개발 공부/Translation

by Ryomi 2023. 11. 8. 15:16

본문

반응형

 

TypeScript is a popular programming language that offers static type checking and advanced features for working with complex data structures. One important concept in TypeScript is type narrowing, which allows developers to make precise assertions about the types of variables in their code. In this article, we will explore how to use Type Predicate Functions to narrow types in TypeScript.

타입스크립트는 정적 타입 검사와 복잡한 데이터 구조를 다루기 위한 고급 기능을 제공하는 인기있는 프로그래밍 언어입니다. 타입스크립트에서 중요한 개념 중 하나는 타입 추론을 좁히는(type narrowing) 기능인데, 이는 개발자가 코드 내 변수의 타입에 대해 정확한 단언을 할 수 있게 해줍니다. 이 글에서는 타입스크립트에서 타입 추론을 좁히기 위해 타입 예측 함수(Type Predicate Functions)를 사용하는 방법을 살펴보겠습니다.

 

If you’ve been working with TypeScript for a while, you know that type safety is one of the language’s core features. However, even with the best type system in place, there are scenarios where we need to make more precise assertions about the types of variables in our code. That’s where type narrowing comes in.

타입스크립트를 사용한 지 어느 정도 시간이 지났다면, 타입 안정성이 이 언어의 핵심 기능 중 하나라는 것을 알고 계실 것입니다. 그러나 최고의 타입 시스템을 갖추더라도 코드 내 변수의 타입에 대해 보다 정확한 단언을 해야 하는 상황이 있습니다. 이때 타입 추론을 좁히는(type narrowing) 개념이 필요합니다.

 

Type narrowing allows us to take a type that is too broad and refine it to a more specific type.

Type narrowing은 너무 범용적인 타입을 더 구체적인 타입으로 세분화하는 것을 의미합니다.

 

This is a critical concept because it can prevent errors and make our code more expressive and readable.

이는 에러를 막고 코드를 더 표현력 있고 가독성 좋게 할 수 있으므로 중요한 개념입니다.

 

In this article, we’ll focus on one technique for type narrowing in TypeScript: Type Predicate Functions.

이 글에서, 우리는 타입스크립트에서 타입을 좁히는데 사용되는 한 가지 기술인 타입 예측 함수(Type Predicate Function)에 초점을 맞출 것입니다. 

 

 

Understanding Type Predicate Functions

Type Predicate Functions are functions that return a boolean value and have a type predicate as their return type. A type predicate is a type assertion that checks if an object has a specific property or set of properties. This allows TypeScript to narrow the type of an object based on the result of the type predicate.

타입 예측 함수(Type Predicate Function)은 Boolean 값을 반환하고 반환 타입으로 타입 예측(type predicate)을 가진 함수입니다. Type Predicate는 객체가 특정 속성이나 일련의 속성들을 가지고 있는지 확인하는 타입 선언입니다. 이를 통해 타입스크립트는 타입 예측의 결과에 따라 객체의 타입을 좁힐 수 있습니다.

 

Here is an example of a Type Predicate Function:

타입 예측 함수의 예시

function isString(x: unknown): x is string {
  return typeof x === 'string';
}

 

In this example, the Type Predicate Function isString takes an argument x of type unknown, which could be any value. The function then checks if the typeof x is 'string', and returns true or false accordingly.

예시에서, 타입 예측 함수인 isString은 어떤 값이든 될 수 있는 unknown 타입의 인자 x를 받습니다. 그런 다음 함수는 x의 typeof가 'string'인지 여부를 확인하고  true나  false 를 반환합니다.

 

The return type of the function is x is string, which asserts that x is of type string if the function returns true.

함수의 반환 타입은 'x is string'으로, 함수의 반환값이 true라면 x는 string type임을 선언합니다.

 

You can use Type Predicate Functions in conditional statements to narrow the type of a variable based on the result of the type predicate:

타입 예측의 결과에 따라 변수의 타입을 좁히기 위해 타입 예측 함수를 조건문에 사용할 수 있습니다. 

 

function reverseString(x: unknown){
  if (isString(x)) {
    return x.split('').reverse().join('');
  }
	return null
}

 

In this example, the function reverseString takes an argument x of type unknown, which could be any value. The function then calls the Type Predicate Function isString to check if x is a string. If isString(x) returns true, then x is treated as a string and can be reversed using the split, reverse, and join string methods.

위 예시에서 함수 reverseString은 어떤 값이든 될 수 있는 unknown 타입의 x를 인자로 받습니다. 그럼 함수는 타입예측함수인 isString을 호출하여 x가 문자열인지 확인합니다. 만약 isString(x)가 true를 반환한다면, x는 문자열로 처리되고 string method인 split, reverse, join을 사용해 뒤집을 수 있습니다.

 

Pros and Cons of Using Type Predicate Functions for Type Narrowing

Type predicate functions are a powerful tool for type narrowing in TypeScript, but like any technique, they have their pros and cons.

타입 예측 함수는 타입스크립트에서 타입을 줄이는데 사용되는 강력한 도구이지만, 모든 기술이 그러하듯 장단점이 있습니다.

 

One of the major advantages of type predicate functions is that they provide a way to express complex type relationships in a readable and understandable way. They allow you to define custom functions that not only perform a specific task but also return a boolean value that tells TypeScript whether a variable is of a particular type. This can make your code more expressive and self-documenting.

타입 예측 함수의 주된 장점 중 하나는 복잡한 타입 관계를 가독성 좋고 이해하기 쉽게 표현할 수 있다는 점입니다. 타입 예측함수는 특정 작업을 수행하는 동시에 변수가 특정 타입인지 여부를 타입스크립트에게 알려주는 boolean 값을 반환하는 커스텀 함수를 정의할 수 있게 해줍니다. 이는 코드를 더 표현적이고 자기 설명적인 방식으로 작성할 수 있습니다.

 

They can also be useful when you need to perform dynamic type checks on an object. For example, imagine you have a function that takes an object as an argument, but you’re not sure whether the object has a specific property. With a type predicate function, you can check for the presence of that property and narrow the type of the object to include that property.

타입 예측 함수는 객체의 동적인 타입 검사를 수행해야할 때 유용합니다. 예를 들어, 객체를 인자로 받는 함수가 있는데, 그 객체가 특정 속성을 가지고 있는지 여부를 확신할 수 없는 경우가 있습니다. 타입 예측 함수를 사용하면 해당 속성의 존재를 확인하고 객체의 타입을 해당 속성을 포함하는 타입으로 좁힐 수 있습니다. 

 

On the downside, type predicate functions can be more difficult to set up and use than conditional blocks. They require you to define custom functions and may require more code to get up and running.

반면에, 타입 예측 함수는 조건문 보다 만들고 사용하기 더 어려울 수 있습니다. 타입 예측 함수는 사용자 정의 함수를 정의하고 실행시키는데 더 많은 코드가 필요할 수 있습니다.

 

Additionally, type predicate functions can add complexity to your code, making it harder to read and understand. This can be particularly true when working with a large codebase.

추가적으로, 타입 예측 함수는 코드를 복잡하게 만들어 코드를 읽고 이해하기 어렵게 만들 수 있습니다. 특히 큰 코드 베이스 환경에서 작업할 때 이러한 문제가 두드러질 수 있습니다. 

 

One of the biggest risks of using type predicates for type narrowing is the possibility of writing incorrect predicates that lead to unexpected or undesired type narrowing. This can result in runtime errors or unexpected behavior, which can be difficult to diagnose and fix.

타입을 좁히기 위해 타입 예측을 사용하는데 가장 큰 위험 중 하나는 잘못된 예특을 작성하여 예상치 못하거나 원치 않은 타입 좁힘이 발생할 수 있다는 점입니다. 이는 런타임 에러나 예상치 못한 동작을 초래할 수 있으며, 이를 확인하고 수정하기 어려울 수 있습니다.

 

It’s important to note that while type predicates can be a powerful tool for type narrowing, they are not the only way to achieve this. Another common approach is to use type assertions with the as keyword, which allows you to tell the TypeScript compiler to treat a value as a particular type, even if the compiler is not able to infer it.

타입 예측이 타입 좁힘에 강력한 도구일 수 있지만 타입 예측이 유일한 방법은 아닙니다. 다른 일반적인 방법은 'as' 키워드로 타입단언을 하는 것입니다. 이는 타입스크립트 컴파일러가 해당 타입을 추론할 수 없는 경우에도 값을 특정 타입으로 취급하도록 할 수 있습니다. 

 

However, type assertions also carry some risks. They can lead to runtime errors if the asserted type is incorrect, and can also make your code less type-safe by allowing you to bypass type checking. As with type predicates, it’s important to use type assertions judiciously and with a clear understanding of their risks and benefits.

그러나, 타입단언 역시 몇몇 위험을 가지고 있습니다. 부정확한 타입 단언은 런타임 에러를 야기할 수 있고 타입 체크를 우회할 수 있어 코드의 타입 인정성을 감소시킬 수 있습니다. 타입예측과 마찬가지로, 타입단언을 현명하게 사용하고 위험과 이점을 분명히 이해하는 것이 중요합니다. 

 

In this scenario Type Predicates and Type Assertions behaves as a lie to the type system where you as a developer say “I know more about this type than the compiler” and force the type to be the desired one, as an example:

이 시나리오에서, 타입 예측과 타입 단언은 타입 시스템에 거짓말 하는 것과 같습니다. 개발자로서 '나는 컴파일러보다 이 타입에 대해 더 많이 알고 있어'라고 말하며 원하는 타입으로 강제합니다. 예를 들어:

function isString(x: unknown): x is string {
  return typeof x === 'number';
}

 

The above example check if x is a number, and if that is true then the predicate say that the variable is a string. If later you use that type predicate, TS assume that the variable is an string and the type safety will be lost.

위 예시는 x가 숫자인지 여부를 확인하고, 만약 그렇다면 predicate는 변수를 문자열로 선언합니다. 이후에 해당 타입 예측을 사용하면 타입 스크립트는 변수를 문자열로 간주하고 타입 안정성이 손실될 수 있습니다.

 

Best Practices for Using Type Predicate Functions for Type Narrowing

To use Type Predicate Functions effectively, it is important to follow best practices and guidelines. Here are some tips for working with Type Predicate Functions:

타입 예측 함수를 효율적으로 사용하기 위해  best practice와 가이드라인을 따르는 것은 중요합니다. 타입 예측 함수로 작업하는 몇가지 팁이 있습니다.

 

  • Define Type Predicate Functions carefully and ensure they are properly typed.
  • Use clear and descriptive names for Type Predicate Functions.
  • Use Type Predicate Functions only when they are appropriate and necessary.
  • Consider alternative approaches to type narrowing, such as conditional blocks or discriminated unions.
  • Use automated testing and code analysis tools to detect potential errors or inconsistencies in the program.

 

  • 타입 예측 함수를 신중하게 정의하고 올바르게 타입화 되어있는지 확인하세요
  • 타입 예측 함수에 명확하고 설명적인 이름을 사용하세요
  • 타입 예측 함수를 적절하고 필요한 경우에 사용하세요
  • 조건문이나 차별화된 유니온과 같이 타입 좁힘에 대안적인 접근 방식을 고려하세요
  • 프로그램에서 잠재적인 에러나 일관성 문제를 감지하기 위해 자동화된 테스트나 코드 분석 도구를 사용하세요

 

 

Conclusion

Type Predicate Functions are a powerful tool for type narrowing in TypeScript. By using Type Predicate Functions, developers can make their code more expressive, easier to read and maintain, and less error-prone. However, it is important to understand the pros and cons of using Type Predicate Functions, and to follow best practices and guidelines for working with them. By doing so, you can create more robust and reliable applications with TypeScript.

타입 예측 함수는 타입스크립트에서 타입을 좁히는데 강력한 도구입니다. 타입 예측 함수를 사용하면 코드를 더 표현적이고 가독성 및 유지보수를 용이하게 하며 에러를 줄이도록 만들 수 있습니다. 그러나, 타입 예측 함수를 사용하는 것의 장단점을 이해하고 이를 사용할 때 best practice와 가이드라인을 따르는 것이 중요합니다. 이렇게 하므로써 타입스크립트를 사용해 더 견고하고 신뢰할 수 있는 어플리케이션을 만들 수 있습니다.

 

reference) 

 

What are Type Predicates in Typescript?

TypeScript is a popular programming language that offers static type checking and advanced features for working with complex data structures. One important concept in TypeScript is type narrowing…

medium.com

 

 

 

 

Check if a String is in Union type in TypeScript | bobbyhadz

A step-by-step guide on how to check if a string is in a union type in TypeScript.

bobbyhadz.com

 

Documentation - Narrowing

Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.

www.typescriptlang.org

 

반응형

관련글 더보기

댓글 영역