Issue
I wrote the following code.
type NumAndStr = { num: number; str: string };
type A<T> = (item: T) => {
key: keyof T;
func: (value: T[keyof T]) => void;
};
const test: A<NumAndStr> = (item) => {
return {
key: "num",
func: (value) => {}, // I expect 'value: number'
};
};
However, since the type of 'value' is 'number | string', I fixed the code as follows
type NumAndStr = { num: number; str: string };
type B<T> = <K extends keyof T>(
item: T,
) => {
key: K;
func: (value: T[K]) => void;
};
// error!
const test: B<NumAndStr> = (item) => {
return {
key: "num",
func: (value) => {},
};
};
How can I get rid of the error?
Solution
This might be your help.
but you have to change some code
can you confirm the below code?
type B<T extends {}, K = keyof T> = (
item: any,
) => {
func: (value: K extends keyof T ? T[K] : never) => void;
};
// correct
const test1: B<NumAndStr, 'num'> = (item) => {
return {
func: (value) => {
// value is expected as a number
},
};
};
Answered By - Joonseo Lee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.