Is there a way to disable Weak Type Detection introduced with Typescript Version 2.4?

652 views Asked by At

With Typescript version 2.4 weak type detection was added. Now I agree this is a great feature and will help catch a whole bunch of bugs for when you are assigning a value to a type that doesn't have a single property match for the type's optional properties.

Unfortunately for a large project originally written in Javascript and then migrated to Typescript there will be cases where the weak type loophole is used.

To allow for an easy migration to TS 2.4 and then the gradual removal of all weak type offences - is anyone aware of a flag or hack to disable the weak type detection temporarily?

2

There are 2 answers

0
millsp On

There is no compiler flag, but I can recommend you ts-migrate. It will transform your existing js to ts code with any where inference does not work.

0
Ivan Sanz Carasa On

Usually this error is thrown when intersecting full optional types (aka object with only optional properties).

Sometimes when writing generic library code, this is something you want to do, even if the intersection results in a full optional type too.

Normal TS intersections won't let you intersect weak types, but you can implement the intersection yourself:

export type WeakIntersect<T, U> = Record<string, never> extends T
  ? Record<string, never> extends U
    ? T & U // fallback to compiler check for weak types
    : U
  : Record<string, never> extends U
    ? T
    : T & U
FullyOptional1 & FullyOptional2 // error
WeakIntersect<FullyOptional1, FullyOptional2> // ok

It is also possible to avoid the error when using extends on a weak type:

export type AllowWeakType<T> = Record<string, never> extends T ? any : T
T extends FullyOptional // error
T extends AllowWeakType<FullyOptional> // ok