Created
May 18, 2025 16:53
-
-
Save mikr13/c4a3175b1ec84f7994275d3cd1119872 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const colorMap = { | |
red: "#f00", | |
green: "#0f0", | |
blue: "#00f", | |
} as const; | |
type Color = keyof typeof colorMap; | |
type LooseAutocomplete<T extends string> = T | (string & {}); | |
function setColor(color: LooseAutocomplete<Color>) { | |
// accepts "red", "green", "blue" with autocomplete | |
// also accepts any other string without error | |
} | |
// Valid usages | |
setColor("red"); // ✅ autocomplete | |
setColor("purple"); // ✅ no autocomplete, but allowed | |
setColor("green"); // ✅ autocomplete |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment