← Back to list

Deep Dive in to typescript- infer, extends and predicates

In Typescript there are too many features but on regular basis we are using some limited features only. Some of the features are not easy…

Vinay Mittal in Frontend Weekly · 2022-02-16 10:23 · 114 claps · 4.1 min read
#typescript #infer #predicate #typescript-extends #typescript-features
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Deep Dive in to typescript- infer, extends and predicates

Image from Unsplash

Image from Unsplash

In Typescript there are too many features but on regular basis we are using some limited features only. Some of the features are not easy to understand because these are not used frequently. So, here we will discuss about these features and understand the uses.

The *extends *Keyword In Typescript constraints are expressed using *extends *keyword. T extends K means that value of T is also the type K. In other words, let say we have a conditional type T extends U ? X : Y that means when T is assignable to U the type is X, otherwise the type is Y .

[embed]Example extends Keyword

In the above example let say we have some dynamic data that can be string or number. so, here T extends string means, if T is a string type then we are returning string as a type otherwise number. We are using extends as conditional types in the example above, you can read more about this in typescript documentation

[embed]Documentation - TypeScript 2.8 TypeScript 2.8 introduces conditional types which add the ability to express non-uniform type mappings. A conditional…www.typescriptlang.org

The *infer* Keyword infer keyword is describe as unwrapping a type. Let’s understand this by using an example

[embed]Problem with without infer

[embed]

we have a describePerson function and on line 15 we are calling that function with johnData but typescript will give error in that case because hobbies are incompatible. As in the describePerson function type of hobbies is a tuple and we are passing hobbies as string[]. We can fix it by using infer.

[embed]infer keyword uses

Here we are using infer keyword to deduce the type of first argument from the type of describePerson function. describePerson takes one argument (person) and we want type of that argument so, we are using infer here to get the type of that argument. Let’s understand this step by step:-

  • Problem Statement:- type of hobbies are incompatible with parameter of describePerson function. One solution is like we can make an interface and assign that to both person argument as well as johnData object. But the issue is, if the implementation of describePerson function is in shared library and we can’t make any changes in that. so, in that case we want type of that parameter.
  • Step 1:- Make a generic type type GetFirstArgType<T>
  • Step 2:- We are passing T as typeof describePerson on line 11.
  • Step 3:- Final output of this should be type of first parameter. T extends (first: infer K) => anystates that if typeof describePerson i.e. (T) is assignable to (first: infer K) => any . So, here we know that describePerson function take one parameter (person) and return type is string . We use infer keyword to get the type of parameter and return type is any for general purpose use. If we replace any with string it works well for this use case but not for all.
  • Step 4:- If T is assignable to (first: infer K) => any then we are returning type of first argument i.e. K otherwise it can be any type.
  • Step 5:- Final output will be K , as T is the typeof describePerson is assignable to (first: infer K) => any. Awesome huh?

There are multiple use cases of infer. Let’s understand some of them with an example:-

[embed]infer in other scenarios

Type Predicates A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature.

[embed]With and without Type Predicates

In the above example we have two methods, isString which returns boolean and argIsString which returns a predicate s is string. In toUpperCase method there is a if statement *if(isString(x)) { x.toUpperCase(); // x is still of type unknown } and *inside that type of x is still unknown. While in other case inside toLowerCase we are calling argIsString method if(argIsString(x)) { x.toUpperCase(); // type of x is string here } and inside if block type of x is string. The difference between isString is returns boolean while argIsString return a predicate s is string and implementation of both the methods is same. So, typescript can infer type when we use predicates.

There are other many use cases, Let’s check one of them with an example:-

[embed]Type Predicates

In above example we have a cat class which implements Pet interface and creating an instance of that class. But we can’t call meow method because typescript doesn’t know the species of p object is ’cat’ 🐈 or ‘dog’ 🐕 . So, on line 14 we have a method petIsCat which will return type as predicate pet is cat and typescript can infer the type in this case.

**const assertions **const assertion in typescript used for making properties of an object as readonly and array in to readonly tuples and other datatypes variables to readonly. It’s also works with nested objects. Let’s check this with an example.

[embed]

In the above example we can see const assertion make all the properties as readonly in the case object and we can’t update the value of a deep nested object property. Also it make variables as constant which are declared with let. This help us lot when we declare an object with const keyword but we don’t want to update nested properties.

When we give an object a Readonly<> type, in that case we can also update the value of the nested properties but const assertion solves our problem in that case. Let’s check this with an example:-

[embed]

There are some caveats of const assertion.

[embed]

we can push the elements in contents array of foo and foo is using as const assertion because in the foo we are providing only instance of that array(arr). This will fail when we provide instance as property values . On the other hand in the case of arrwithconst we can’t push element because it was using as constassertion.

Summary These are some the features that are available in typescript in earlier versions but we are not regularly using them. These features helps a lot while development, features like const assertion, infer and type predicates makes our life easier while coding and helps in writing bug free code.

References https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html https://www.typescriptlang.org/docs/handbook/2/objects.html?#readonly-properties https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates


메타데이터
post_id
baeb5628cf59
slug
typescript-features-you-should-know-baeb5628cf59
url
https://medium.com/front-end-weekly/typescript-features-you-should-know-baeb5628cf59
canonical_url
https://medium.com/front-end-weekly/typescript-features-you-should-know-baeb5628cf59
author_url
https://medium.com/@vinaykrmittal
status
ok
fetched_at
2026-07-27 12:21:05