Issue
If I set listData[index][field] = newValue as any
, it's working, but I don't want to use any.
I still try to use newValue: string | number | Date
still shows the error
How do I let the typescript working for the setting listData[index][field] = newValue
?
interface Sons {
name: string;
address?: string;
date?: Date;
age?: number;
}
interface Parents extends Sons {
height: string;
}
const parentList: Parents = {
name: '',
height: '',
}
const listData: Parents[] = [parentList]
class Test {
update<K extends keyof Parents>(index: number, field: K, newValue: string ) {
// Type 'string' is not assignable to type 'Parents[K]'.
// Type 'string' is not assignable to type 'never'
listData[index][field] = newValue
}
Solution
You can use Parents[K]
instead of string
for newValue
. This is called an Indexed Access type which dynamically looks up the type of a given property key (K
) on the Parents
interface
.
interface Sons {
name: string;
address?: string;
date?: Date;
age?: number;
}
interface Parents extends Sons {
height: string;
}
const parentList: Parents = {
name: '',
height: '',
}
const listData: Parents[] = [parentList]
class Test {
update<K extends keyof Parents>(index: number, field: K, newValue: Parents[K] ) {
listData[index][field] = newValue;
}
}
declare const test: Test;
test.update(0, "height", "very tall");
test.update(0, "date", new Date());
Answered By - Behemoth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.