Search Terms
generic constraint property type keyof
Suggestion
To be able to constrain the type of the property of an object using a keyof type.
Use Cases
Code speaks better than me:
function manageArrayProperty<TObj, TKey extends keyof TObj>(obj: TObj, key: TKey) {
// obj[key] has to extend array
obj[key].forEach(...);
}
Examples
This requires a generic declaration that doesn't define a type but only a constraint
function manageArrayProperty<
TObj,
TKey extends keyof TObj,
TObj[TKey] extends any[]
>(obj: TObj, key: TKey) {
// this is fine
obj[key].forEach(...);
}
Previous attempts
I tried to achieve that in different ways, I can create a type constrained to TObj[TKey] and any[] but that doesn't mean TObj[TKey] extends array.
function manageArrayProperty<
TObj,
TKey extends keyof TObj,
TProp extends TObj[TKey] & any[]
>(obj: TObj, key: TKey) {
// INVALID: obj[key] can not be an array
obj[key].forEach(...);
}
Checklist
My suggestion meets these guidelines:
Search Terms
generic constraint property type keyof
Suggestion
To be able to constrain the type of the property of an object using a
keyoftype.Use Cases
Code speaks better than me:
Examples
This requires a generic declaration that doesn't define a type but only a constraint
Previous attempts
I tried to achieve that in different ways, I can create a type constrained to
TObj[TKey]andany[]but that doesn't meanTObj[TKey]extends array.Checklist
My suggestion meets these guidelines: