I am making a combobox component which takes two parameters:
options: a series of objects to select fromdisplaytextKeyname: a string which represents the name of a key to look at within eachoptionwhich contains a string to display as the name
Here is a simplified example of this in use:
type ComboboxProps<T> = {
options: T[];
displaytextKeyname: string;
}
const Combobox = ({
options,
displaytextKeyname
}:ComboboxProps<unknown>) => {
options.forEach(o => console.log(o[displayTextKeyname])
}
I am looking to make an object that would be suitable as type T above. The idea is this is designed in such a generic way that said field could be called "description", "longname", "name" or whatever. All that is required is that it is a string.
Currently I have attempted it in the following ways:
Approach 1 - require all string values
type ComboboxOption = {
[key: string]: string;
};
const foo: ComboboxOption = {
a: "123",
b: 456, // Type 'number' is not assignable to type string
};
Approach 2 - allow all values
type ComboboxOption = {
[key: string]: unknown;
};
const foo: ComboboxOption = {
a: "123",
b: 123,
};
// This allows objects which do not have at least one key with a string value
const bar: ComboboxOption = {
b: 123,
};
Approach 3 - extend interface
interface IComboboxOption {
[key: string]: string;
}
//Interface 'IComboboxOptionExt' incorrectly extends interface 'IComboboxOption'.
//'string' index signatures are incompatible.
//Type 'unknown' is not assignable to type 'string'
interface IComboboxOptionExt extends IComboboxOption {
[key: string | number | symbol]: unknown;
}
Is this beyond typescript's type system or am I just thinking about this entirely wrong?