typescript type_error ai_generated true

TS2344: Type 'X' does not satisfy the constraint 'keyof Y'. Type 'X' is not assignable to type 'string | number | symbol'.

ID: typescript/ts-utility-type-error

Also available as: JSON · Markdown
86%Fix Rate
88%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Utility types like Pick, Omit, and Record have constraints on their type parameters. The provided keys must exist on the target type.

generic

Workarounds

  1. 90% success Ensure keys passed to Pick/Omit are actual properties of the type
    interface User { id: string; name: string; email: string; }
    // Correct: all keys exist on User
    type UserPreview = Pick<User, 'id' | 'name'>;
    // Error: 'role' doesn't exist on User
    // type Bad = Pick<User, 'id' | 'role'>;

    Sources: https://www.typescriptlang.org/docs/handbook/utility-types.html

  2. 85% success Use Extract to safely filter keys that exist on the type
    type SafePick<T, K extends string> = Pick<T, Extract<K, keyof T>>;
    // Now SafePick<User, 'id' | 'role'> = Pick<User, 'id'>
    // 'role' is silently ignored instead of erroring

    Sources: https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union

Dead Ends

Common approaches that don't work:

  1. Use any as the type argument to bypass constraints 75% fail

    Results in a useless type that doesn't constrain anything at call sites

Error Chain

Leads to:
Preceded by:
Frequently confused with: