Trying to get the following TypeScript type expression correct to have a local
Trying to write a type smart function called getValue(string, defValue?) that returns either a string or the default value if the key isn't found. The function should have the type of string | typeof defaultValue the lookupValue() function has the correct typing to support this.
At this point have tried 4 different variations of the approach, three of which fail in compilation or usage, the last case doesn't fully handle the type inputs but does compile.
// This function is good -- correctly handling the types
lookupValue<D>(record: string[], key: string, defvalue: D): D | string {
const index = this.columnHeaders[key];
const v = index !== undefined ? record[index] : undefined;
return v === undefined || v === "" ? defvalue : v.trim();
}
someFunction(record: string[]) {
// -- Test 1
const getValue = <T>(key: keyof typeof COLUMNS, defvalue = undefined) => lookupValue(record, key, defvalue);
// Argument of type '""' is not assignable to parameter of type 'undefined'.
const bigDef = getvalue("testBig", "something");
// -- Test 2
// Type 'undefined' is not assignable to type 'T'.
const getValue = <T>(key: keyof typeof COLUMNS, defvalue: T = undefined) => lookupValue(record, key, defvalue);
// -- Test 3
// Won't compile since the defvalue is "T | undefined" which isn't valid
const getValue = <T>(key: keyof typeof COLUMNS, defvalue?: T) => lookupValue(record, key, defvalue);
// -- Test 4
// Compiles but is wrong since the following getValue "works"
const getValue = <T = undefined>(key: keyof typeof COLUMNS, defvalue?: T) => lookupValue(record, key, defvalue as T);
// Works - but shouldn't
const foo: string = getValue("test");
}
The objective is to have something that fills this requirement:
const big = getvalue("testBig"); // Should be type of string | undefined
const bigDef = getvalue("testBig", "something"); // Should be type string
COLUMNS? Also how doesTrelate toCOLUMNSideally we would want there to be a relation between column type andTotherwise this is no better thenany.