Reputation: 2144
I'm having trouble with the following:
interface MyType {
[key: number]: number;
}
function myfunc<MyType>(map: MyType, key: keyof MyType) {
map[key] = 4; // Error: type '4' is not assignable to type MyType[keyof MyType]
}
I'm not sure what I need to do to make it safe to assign something to map[key]?
Upvotes: 1
Views: 49
Reputation: 59942
The <MyType>
on myfunc
introduces a template parameter that is different from interface MyType
. Just get rid of it and it'll work.
function myfunc(map: MyType, key: keyof MyType) {
map[key] = 4;
}
Upvotes: 1
Reputation: 120410
In your function, you have (for unknown reasons) defined a generic type variable MyType
which occludes your actual MyType
declaration. This means that within the scope of the function, MyType
refers to a generic type for which no further information can be inferred... hence the error.
It needs to change from
function myfunc<MyType>(map: MyType, key: keyof MyType){//...
to just
function myfunc(map: MyType, key: keyof MyType){//...
Upvotes: 1