Skip to content

Commit

Permalink
Jsonify: Fix handling of nested objects with only a name property (
Browse files Browse the repository at this point in the history
…#691)

Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
donovanhiland and sindresorhus authored Sep 26, 2023
1 parent 7950542 commit 5351533
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
13 changes: 10 additions & 3 deletions source/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,16 @@ type BaseKeyFilter<Type, Key extends keyof Type> = Key extends symbol
? never
: Type[Key] extends symbol
? never
: [(...arguments_: any[]) => any] extends [Type[Key]]
? never
: Key;
/*
To prevent a problem where an object with only a `name` property is incorrectly treated as assignable to a function, we first check if the property is a record.
This check is necessary, because without it, if we don't verify whether the property is a record, an object with a type of `{name: any}` would return `never` due to its potential assignability to a function.
See: https://github.com/sindresorhus/type-fest/issues/657
*/
: Type[Key] extends Record<string, unknown>
? Key
: [(...arguments_: any[]) => any] extends [Type[Key]]
? never
: Key;

/**
Returns the required keys.
Expand Down
11 changes: 11 additions & 0 deletions test-d/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,17 @@ expectType<{a: any}>(objectWithAnyProperty);
declare const objectWithAnyProperties: Jsonify<Record<string, any>>;
expectType<Record<string, any>>(objectWithAnyProperties);

// Test for `Jsonify` support for nested objects with _only_ a name property.
// See https://github.com/sindresorhus/type-fest/issues/657
declare const nestedObjectWithNameProperty: {
first: {
name: string;
};
};
declare const jsonifiedNestedObjectWithNameProperty: Jsonify<typeof nestedObjectWithNameProperty>;

expectType<typeof nestedObjectWithNameProperty>(jsonifiedNestedObjectWithNameProperty);

/// #629
// declare const readonlyTuple: Jsonify<readonly [1, 2, 3]>;
// expectType<readonly [1, 2, 3]>(readonlyTuple);

0 comments on commit 5351533

Please sign in to comment.