Reputation: 26558
I have the following types:
interface IFilterField <T extends FilterFieldValue > {
defaultValue: T
displayStr?: string
}
interface IFilterFields = {
costMax: IFilterField<number>
costMin: IFilterField<number>
.....
}>
When I try to type an object that will link between the filterField and the type of its` value, this works:
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
[K in keyof FiltersKeys]: IFilterFields["costMin"|"costMax"]["defaultValue"]
}
But this fails:
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
[K in keyof FiltersKeys]: IFilterFields[K]["defaultValue"]
}
Even though the constraint is pretty much the same.
Error:
[ts] Type 'K' cannot be used to index type 'IFilterFields'. [2536]
[ts] Type '"defaultValue"' cannot be used to index type 'IFilterFields[K]'. [2536]
Why is this error occuring?
How can I acheive the purpose of a mapped type, which follows this principles: A new type T2 has some of the keys of type T1, and for each such key typeof T1[key] equals typeof T2[key][SomeFieldName]?
Upvotes: 2
Views: 433
Reputation: 26558
I found my error. Since FiltersKeys
is already a union of keys/strings, there is a reduntand keyof in [K in keyof IfilterFields]
.
Upvotes: 2
Reputation: 3387
Because FiltersKeys is extended from IFilterFields, therefore it could contain different keys. You can use
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
[K in keyof IFilterFields]: IFilterFields[K]["defaultValue"]
}
Upvotes: 1