我希望创建一个类型定义,可以包含已知的字符串字面量或任何字符串,例如:
type IColor = "blue" | "green" | "red" | string;
TS 对这种类型定义不会发出警告,但它也无法帮助智能感知。我的目标是定义一个函数,该函数可以接受已知颜色或任何颜色字符串。
const knownColors = {
green: "#66bb6a",
red: "#ef9a9a",
blue: "#81d4fa",
} as const;
function getColor(color: keyof typeof knownColors | string): string {
if (color in knownColors)
return knownColors[color as keyof typeof knownColors];
return color;
}
使用方法:
getColor("blue"); // "blue" is a known color, returns "#81d4fa"
getColor("black"); // "black" is not a known color, returns "black"
我希望Intellisense更加智能化。
getColor("_ // as I type this line,
^ blue // I want these suggestions
^ green
^ red
type-fest
的包,您可以使用LiteralUnion
来启用自动完成:https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts - konsalex