When working with an object type (or class type), I am looking to create a function that will take the object and a list of its keys as parameters. However, I specifically want to restrict the keys to only those that are mapped to a value of a certain type, such as strings.
For example:
function shouldOnlyAcceptStringValues(o, key) {
// Implement functionality that relies on the assumption that o[key] is of a specific type, for instance a string
}
const obj = {
a: 1,
b: "test",
c: "bla"
}
const key = "c" as const;
shouldOnlyAcceptStringValues(obj, key); // The keys b and c should be allowed, but not a
I am aware of a method to ensure that the key
exists within o
(regardless of the type of o[key]
):
function shouldOnlyAcceptStringValues<T>(o: T, key: keyof T) {
// Implement functionality that relies on the assumption that o[key] is of a specific type, for instance a string
}
However, this approach would still permit the use of key="a"
, even though it corresponds to a number value.
What I am seeking is a solution like the following:
function shouldOnlyAcceptStringValues<T, K extends keyof T, T[K] extends string>(o: T, key: K)
Unfortunately, this is not valid TypeScript code.
Is there a workaround to achieve this? I am in need of a method to narrow down the set of keys within keyof T
. Subsequently, the function should be able to recognize that o[key]
is a string without explicitly checking the type within the function. Is there a way to accomplish this?