It seemed like I had a good grasp on how to tackle this, but clearly there's a misstep somewhere.
I'm aiming to create a function that acts as a typeguard; its main purpose is to ascertain whether an input is an object containing a specified key of a specific type. The issue I'm facing arises when I try to define U
and use U extends { [K]: V }
because I encounter the following errors:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
'K' only refers to a type, but is being used as a value here.ts(2693)
export const hasAndIsType = <K extends PropertyKey, V extends PossibleTypes, U extends { [K]: V }>(
key: string,
type: PossibleTypes,
) => (x: any): x is U =>
has(key, x) && typeof x[key] === type;
Is there a solution for this dilemma?
Edit:
Initially, I thought it might be a syntax error that could be rectified as:
U extends { [k: K]: V }
However, now I am faced with this error message:
An index signature parameter type must be either 'string' or 'number'.ts(1023)
This persists even when defining the type as:
export const hasAndIsType = <K extends string | number, V extends PossibleTypes, U extends { [k: K]: V }>(