有没有办法只限制参数中的联合类型?

问题描述 投票:0回答:1

我试图将函数的参数限制为仅联合类型。

例如:

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[]>
。多次试验可能没有意义,所以不在这里分享,但我想知道是否有一种方法可以使其成为可能。

typescript
1个回答
0
投票

只需升级泛型类型即可:

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?
© www.soinside.com 2019 - 2024. All rights reserved.