2021-10-05
1209
#typescript
Simohamed Marhraoui
70024
Oct 5, 2021 ⋅ 4 min read

Understanding infer in TypeScript

Simohamed Marhraoui Vue and React developer | Linux enthusiast | Interested in FOSS

Recent posts:

Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

Rahul Padalkar
Apr 17, 2024 ⋅ 9 min read
Web Components Adoption Guide: Overview, Examples, And Alternatives

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

Elijah Asaolu
Apr 16, 2024 ⋅ 11 min read
Using Aws Lambda And Aws Cloudfront To Optimize Image Handling

Using AWS Lambda and CloudFront to optimize image handling

Leverage services like AWS Lambda, CloudFront, and S3 to handle images more effectively, optimizing performance and providing a better UX.

Nitish Sharma
Apr 12, 2024 ⋅ 12 min read
Building Web-Based Terminal Components With Termino.js

Building web-based terminal components with Termino.js

Explore Termino.js, an open source library for integrating web-based terminals into applications, in this introduction article.

Chibuike Nwachukwu
Apr 11, 2024 ⋅ 6 min read
View all posts

6 Replies to "Understanding <code>infer</code> in TypeScript"

  1. A literal [ ‘hello’ , ‘world’ ] in Typescript code is by default typed as a mutable array not a readonly tuple, but you can resolve this with `as const`.

    Although it was a two-arg string array when you created it, Typescript models it as a mutable array, because you could push(), pop() and so on. One way to defeat this type-widening, alex should be declared `as const` which prevents it from being considered mutable and makes push(), pop() a compiler error so it can never vary from being a two-value tuple.

    I really liked the learning associated with infer, (for when you can’t edit the function), but for the case where you can edit the function, I think a better fix is for the person type to be asserted readonly in the first place and to use `as const` when composing person objects, which allows the original code to compile…

    function describePerson(person: Readonly<{
    name: string;
    age: number;
    hobbies: Readonly; // tuple
    }>) {
    return `${person.name} is ${person.age} years old and love ${person.hobbies.join(” and “)}.`;
    }

    const alex = {
    name: ‘Alex’,
    age: 20,
    hobbies: [‘walking’, ‘cooking’] // type is [string, string]
    } as const;

    describePerson(alex)

    Getting this right means that you haven’t type-widened the alex object, to turn e.g. hobbies into [string,string] by declaring it as a Person. When you use `as const` the hobbies property can still be inferred by the editor as being the narrower [‘walking’,’cooking’]. This has saved me a million times where compiler and editor awareness of the values is needed to guard sensitive logic. For example, some other type might be {hobby:’cooking’|’walking’, favouriteOutdoorMeals:string[]} and the compiler can know that both values of alex.hobbies fulfil the hobby value. This is not possible after type-widening them to string.

    See also https://learntypescript.dev/10/l4-readonly-function-parameters and https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md

    You can see the above approach in the playground https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAEwKYGcICcYCNUAKqW6CAFAA7GlgBciASqgIbIIA2AngDwDeAsAChEiMMwC2qeuig4wAcwDcQkc3lTRIcfizLhiABZxcuGBnpNWHHgG0Zc+QBpE9mAoC6APkWIA9L8QoEAp2VCEAX08ASkQBfSxUIKwkAAMAEl4qEgQAOjFJcMQYdEQMrJoctVRCzhYSRDh2ZERmMGb2OAA3VFLM6lyjEzN0HIArODcyACIWtpEpqPCclL1woSEIBBkW0IAPRABeWJVRCQ0AcgBBPfPHE6r6ACYABjv9QdNzRBtzgHdmdgAazc8luiHOmzgwIU53cfgCUE4VCKJTsshBzlcHgiLRKmzAMj0QjQmBw+CI2TAZABqF2USAA

  2. Thank you so much for this great article. I didn’t get a sense of “infer” from official TS guide. But here it described perfectly

  3. This is so COOL! This article let me understand the concept of ‘infer’. Thanks a lot, Marhraoui 🙂

  4. For you who need to infer Function return Promise,

    type PromiseReturnType = T extends Promise ? Return : T
    type FunctionReturnType = T extends (…args: any[]) => infer R
    ? PromiseReturnType
    : any

Leave a Reply