fix(typescript-types): Prevent distribution in IsKeyOf<T,K>

This commit is contained in:
T. R. Bernstein
2025-07-17 16:35:11 +02:00
parent 7decf5ea45
commit 96cf6bbc48
2 changed files with 7 additions and 4 deletions

View File

@@ -1,4 +1,8 @@
import type { If } from './if.js'
import type { IsNever } from './is-never.js'
export type IsKeyOf<T, K> = If<IsNever<T>, false, If<IsNever<K>, false, K extends keyof T ? true : false>>
export type IsKeyOf<Obj, Key> = If<
IsNever<Key>,
false,
[Key] extends [keyof Obj] ? If<IsNever<Obj[Key]>, false, true> : false
>

View File

@@ -13,8 +13,8 @@ expect<IsKeyOf<Example1, 'requiredKey'>>().type.toBe<true>()
expect<IsKeyOf<Example1, 'optionalKey'>>().type.toBe<true>()
expect<IsKeyOf<Example1, 'unknownNonOptionalKey'>>().type.toBe<true>()
expect<IsKeyOf<Example1, 'undefinedNonOptionalKey'>>().type.toBe<true>()
expect<IsKeyOf<Example1, 'neverKey'>>().type.toBe<true>()
expect<IsKeyOf<string, 'toString'>>().type.toBe<true>()
expect<IsKeyOf<Example1, any>>().type.toBe<true>()
expect<IsKeyOf<any, 123>>().type.toBe<true>()
expect<IsKeyOf<any, 'asdf'>>().type.toBe<true>()
@@ -22,11 +22,10 @@ expect<IsKeyOf<any, 'asdf'>>().type.toBe<true>()
expect<IsKeyOf<Example1, 'unknown'>>().type.toBe<false>()
expect<IsKeyOf<object, 'toString'>>().type.toBe<false>()
expect<IsKeyOf<Example1, 'neverKey'>>().type.toBe<false>()
expect<IsKeyOf<Example1, never>>().type.toBe<false>()
expect<IsKeyOf<never, 'toString'>>().type.toBe<false>()
expect<IsKeyOf<never, 'anystring'>>().type.toBe<false>()
expect<IsKeyOf<never, 123>>().type.toBe<false>()
expect<IsKeyOf<any, never>>().type.toBe<false>()
expect<IsKeyOf<undefined, 123>>().type.toBe<false>()
expect<IsKeyOf<Example1, any>>().type.toBe<boolean>()