sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
13.92k stars 528 forks source link

Type `{}` is not assignable to type `PartialDeep<T>` #916

Open tommy-mitchell opened 1 month ago

tommy-mitchell commented 1 month ago

Combining PartialDeep with a generic does not accept an empty object initializer:

import type {PartialDeep, UnknownRecord} from 'type-fest';

type Person = {
  name: string;
  age: number;
};

const mock = <T extends UnknownRecord>(mock: PartialDeep<T> = {}): T => mock as T;
//                                     ~~~~~~~~~~~~~~~~~~~~~~~~~
//=> Error (ts2322): Type `{}` is not assignable to type `PartialDeep<T>`

const person = mock<Person>({name: 'Bob'});
//    ^? const person: Person

Upvote & Fund

Fund with Polar

Max10240 commented 1 month ago

Just my own opinion, it probably has nothing to do with PartialDeep, A simpler example is:

// Type 'string' is not assignable to type 'T'.
//   'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string'.(2322)
const func = <T extends string>(value: T = '') => value;

Because T can be any subtype of UnknownRecord, it could even be never; And if T is never, then mock: PartialDeep<T> is never, in this case {} cannot be assigned to never, so TS made such a complaint.

In addition, the following code is error-free:

import type {PartialDeep, UnknownRecord} from 'type-fest';

// no error here, so "{} is assignable to type PartialDeep<T>"
const foo: PartialDeep<UnknownRecord> = {};