Ts-toolbelt: TS 3.6: Creating a type for "all the optional properties of T, turned mandatory" creates error

Created on 14 Nov 2019  路  3Comments  路  Source: millsp/ts-toolbelt

馃悶 Bug Report

Describe the bug

I'm using React, and have created a type for the defaultProps object. The idea is to take a type, strip it of required properties, then turn the remaining (optional) properties into required properties. This worked great in ts-toolbelt version 4.8 with TypeScript 3.5, but now fails in ts-toolbelt version 4.10 with TypeScript 3.6. (The ts-toolbelt 4.8 version works great in TypeScript 3.6.)

Reproduce the bug

export type DefaultProps<T extends object> = A.Compute<{ [K in O.OptionalKeys<T>]-?: T[K] }>;

Error: "Type 'K' cannot be used to index type 'T'"

Possible Solution

When using the O.OptionalKeys implementation from ts-toolbelt 4.8, it still works:

type OptionalKeys<O extends object> = {
    [K in O.Keys<O>]: {} extends Pick<O, K> ? K : never;
}[O.Keys<O>];

So, at the moment, I yanked the OptionalKeys definition from ts-toolbelt 4.8 for use in my DefaultProps type.

bug

Most helpful comment

Wow, that was a fast fix. I'm very impressed at your dedication to this project.

All 3 comments

Hi @pmarshall, sorry about this. This happened after optimizing performance on Keys types. The fix will be out in a few minutes https://travis-ci.org/pirix-gh/ts-toolbelt/builds/612061398.

Another thing, be aware (and careful) that doing K in O.OptionalKeys<T> will cause to lose a type's field modifiers (you will lose readonly, ?). See this example where I've just removed -?:

export type DefaultProps<T extends object> = A.Compute<{ [K in O.OptionalKeys<T>]: T[K] }>;

type t = DefaultProps<{a?: string}>

This is a known TS limitation.

Wow, that was a fast fix. I'm very impressed at your dedication to this project.

You're welcome! Type safety is very important to me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tonivj5 picture tonivj5  路  3Comments

ctrlplusb picture ctrlplusb  路  6Comments

thesunny picture thesunny  路  4Comments

millsp picture millsp  路  6Comments

millsp picture millsp  路  3Comments