let array: Array<string> = ["hello", "hi"];
// What I want:
// let array: Array<?> = ["hello", "hi"];
// Type should be inferred as Array<string> automatically
Impossible on a variable, however totally possible with a function.
function arrayFunc<T>(array: Array<T>): Array<T> {
return array;
};
let dataFromFunc = arrayFunc(["hello"]);
// T is inferred as string automatically
Now, this seems a bit a weird why I want this, since I can just do let array = [1, 2]
, and have the whole thing be inferred for me as number[]
. However, once the type gets more complicated like an object, I would like to keep the type checking and autocomplete.
type Options<T extends string> = {
a: number,
b: number,
c: T
}[];
And now to declare the variable:
// Ideally: let options: Options<?> = [...]
// Note: NOT let options: Options<any>, I want the exact type inferred, just like a function.
let options: Options<"a" | "b" | "c" | "d"> = [
{
a: 1,
b: 2,
c: "a"
},
{
a: 1,
b: 2,
c: "b"
},
{
a: 1,
b: 2,
c: "c"
},
{
a: 1,
b: 2,
c: "d"
},
];
Putting the generic in myself has it's purpose at times, but I want to just keep adding options in this case and have the generic type inferred automatically. Again, this is possible with a function:
function optionsFunc<T extends string>(options: Options<T>): Options<T> {
return options;
}
let optionsFromFunc = optionsFunc([...]);
// T is automatically inferred as <"a" | "b" | "c" | "d">
However, this seems very weird since now I am passing everything into a runtime function that just returns itself.
You may be wondering why not just create the array directly on the function that uses it? Well, I want to store my options in a separate file and reuse it in multiple parts of my program.
Is there any good way to do this or solve my use case?