我试图将函数的参数限制为仅联合类型。
例如:
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?
正如您在上面的示例中看到的,我尝试使用
readonly
关键字来创建扩展类型。我也尝试过Readonly<string[]>
。多次试验可能没有意义,所以不在这里分享,但我想知道是否有一种方法可以使其成为可能。
只需升级泛型类型即可:
const getSelector = <T extends string>(arg: T[])=>{
return (validType: T) =>{
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?