I'd like to create a type definition for one of known string literals, or any string, e.g:
type IColor = "blue" | "green" | "red" | string;
TS doesn't complain about that type definition, but it also doesn't help with intellisense. My goal would be to define a function that accepts one of known colors or any color string.
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;
}
Usage:
getColor("blue"); // "blue" is a known color, returns "#81d4fa"
getColor("black"); // "black" is not a known color, returns "black"
I want intellisense to be intelligent
getColor("_ // as I type this line,
^ blue // I want these suggestions
^ green
^ red
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…