I am trying to restrict an argument of a function to be only union type.
For example:
type UnionType = readonly string[];
const getSelector = <T extends UnionType>(arg: T)=>{
return (validType: T[number])=>{
return 'data is '+(!arg.includes(validType) ? "NOT " : '') + "included";
}
}
const myFunc = getSelector(["opt1", "opt2", "opt3"] as const); // <== should be fine!
myFunc("opt1"); // auto complete is working!
const myFunc2 = getSelector(["optA", "optB", "optC"]);
myFunc2("optA"); // auto complete is NOT working! since the given options are not const.
// how can I RESTRICT the options as const type?
As you see above example, I tried to make the extended type with readonly
keyword. I also tried Readonly<string[]>
. Multiple trials that might not make sense so not sharing here, but I wonder if there is even a way that there is even a way to make it possible.