Skip to content

Commit

Permalink
Get: Fix handling of paths with number template literal (#968)
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus authored Nov 6, 2024
1 parent a8148ec commit b93f54a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
16 changes: 14 additions & 2 deletions source/get.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,20 @@ type PropertyOf<BaseType, Key extends string, Options extends GetOptions = {}> =
? undefined
: Key extends keyof BaseType
? StrictPropertyOf<BaseType, Key, Options>
: BaseType extends readonly [] | readonly [unknown, ...unknown[]]
? unknown // It's a tuple, but `Key` did not extend `keyof BaseType`. So the index is out of bounds.
// Handle arrays and tuples
: BaseType extends readonly unknown[]
? Key extends `${number}`
// For arrays with unknown length (regular arrays)
? number extends BaseType['length']
? Strictify<BaseType[number], Options>
// For tuples: check if the index is valid
: Key extends keyof BaseType
? Strictify<BaseType[Key & keyof BaseType], Options>
// Out-of-bounds access for tuples
: unknown
// Non-numeric string key for arrays/tuples
: unknown
// Handle array-like objects
: BaseType extends {
[n: number]: infer Item;
length: number; // Note: This is needed to avoid being too lax with records types using number keys like `{0: string; 1: boolean}`.
Expand Down
13 changes: 13 additions & 0 deletions test-d/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,16 @@ expectTypeOf<Get<{a: readonly []}, 'a[0]'>>().toEqualTypeOf<unknown>();
// Test empty path array
expectTypeOf<WithDictionary>().toEqualTypeOf<Get<WithDictionary, []>>();
expectTypeOf<WithDictionary>().toEqualTypeOf<Get<WithDictionary, readonly []>>();

// eslint-disable-next-line no-lone-blocks
{
type Foo = {
array: string[];
};

type FooPaths = `array.${number}`;
expectTypeOf<Get<Foo, FooPaths>>().toEqualTypeOf<string | undefined>();

type FooPaths2 = 'array.1';
expectTypeOf<Get<Foo, FooPaths2>>().toEqualTypeOf<string | undefined>();
}

0 comments on commit b93f54a

Please sign in to comment.