Issue
I have this basically:
type RowType = {
fooLow: number;
fooMid: number;
fooHigh: number;
barLow: string;
barMid: string;
barHigh: string;
}
type ErrorType = {
fooLow?: boolean;
fooMid?: boolean;
fooHigh?: boolean;
barLow?: boolean;
barMid?: boolean;
barHigh?: boolean;
}
type NumberKeyType = 'fooLow' | 'fooMid' | 'fooHigh';
type StringKeyType = 'barLow' | 'barMid' | 'barHigh';
Then I use it like this:
const row = {
fooLow: 1;
fooMid: 2;
fooHigh: 3;
barLow: 'hello';
barMid: 'world';
barHigh: 'asdf';
}
check<NumberKeyType>(row, 'fooLow', 'fooMid', 'fooHigh')
check<StringKeyType>(row, 'barLow', 'barMid', 'barHigh')
function check<T>(
rowData: RowType,
low: T,
middle: T,
high: T
): ErrorType {
const newError: ErrorType = {};
if (
rowData[low] ||
rowData[middle] ||
rowData[high]
) {
let isMissing = false;
if (!rowData[low]) {
isMissing = true;
newError[low] = true;
}
if (!rowData[middle]) {
isMissing = true;
newError[middle] = true;
}
if (!rowData[high]) {
isMissing = true;
newError[high] = true;
}
// don't need to compute relations if any are missing.
if (isMissing) {
return newError;
}
}
return newError;
}
It is returning the following error:
Type 'T' cannot be used to index type 'RowType'
What must I do differently to get it to allow for passing in T
? I would like to use typed generics to make it so my function is more reusable, rather than having 1 function for numbers and a second one for strings (and in my case it's slightly different, I have a few more variations). So I would like to use type generics if possible, not sure what I'm doing wrong.
Solution
You'll need to add a constraint or else T
could be any type:
function check<T extends NumberKeyType | StringKeyType>(...) { ... }
function check<T extends keyof RowType>(...) { ... }
Answered By - kelly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.