I am trying to create a function similar to the "in" operator with key suggestion in TypeScript. I am facing an issue with typing the return type as Pick<T, K>
showing a warning, even though the code is working perfectly fine.
const users = {
"Alice": {
"id": 1,
"name": "Alice",
"age": 30,
"isActive": true
},
...
}
type AllKeys<T> = T extends unknown ? keyof T : never
//@ts-ignore
function hasKey<T extends object, K extends AllKeys<T>>(obj: T, key: K): obj is Pick<T, K> {
return key in obj
}
const userKey = "Alice" as keyof typeof users
const user = users[userKey]
if ("hasSubscription" in user) {
user.hasSubscription
}
if (hasKey(user, "isVerified")) {
user.isVerified
}
/** Pick<T, K> is warning
fixing or better solution
*/
//@ts-ignore
function hasKey<T extends object, K extends AllKeys<T>>(obj: T, key: K): obj is Pick<T, K> {
return key in obj
}