Issue
I write a function: createMyForm , I hope that fields[].prop must be the property of initialValue, but this code can’t do it,
type FieldConfig<K> = {
prop: K;
value?: any;
}
function createMyForm<
V extends Record<string, any>,
K extends string = Exclude<keyof V, symbol | number>,
>(
{ initialValue, fields = [] }: {
initialValue: V;
fields?: FieldConfig<K | `${K}.${string}` | `${K}[${string | number}]`>[];
}) { return; }
const initVal = { a: 1, b: '2' };
// why x2 not show error 😡
createMyForm({ initialValue: initVal, fields: [{ prop: 'x2' } as const]})
Solution
Your type parameter for K:
K extends string = Exclude<keyof V, symbol | number>
Means that K can be any string, but by default is a string key of V. I think probably you just want:
K extends Exclude<keyof V, symbol | number>
K should always be a string key of V. You don't need a default case for K because it can always be inferred from required property initialValue, even though fields is optional.
Answered By - lawrence-witt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.