A warning:
I wanted this for some react components that I wanted to take some string-valued prop keys that should be anything but a set of localization system lookup constants, and while the accepted answer from ccarton above does the trick (applied here, too: Playgrounds), it is also worth mentioning that typescript's error messages when your code fails to meet the type constraint, are completely rubbish, and actively misleading – example from the playground link / code below:
<DemandsNonLocKeys title={"illegal"} text={"!"}/>; // fails, as wanted 🤠
Hover the marked-as-illegal title
attribute's squigglies (yes, not text
), and you currently (* with typescript 4.7.2, in case this ever improves in some direction) see:
(property) title: "!"
Type '"illegal"' is not assignable to type '"!"'.(2322)
So, while this hack is excellent for things like preventing commit hooks from committing buggy code, it relies on developers to have tribal knowledge about what is wrong when these errors strike, as the error message is completely off the rails.
Complete example code, in case Playgrounds ever dies:
import * as React from "react";
const translations = {
"illegal": "otillåten",
"forbidden": "förbjuden"
} as const;
type LocDict = typeof translations;
type LocKey = keyof LocDict;
type LocString = LocDict[LocKey]; // stricter constraint than NotLocKey
type NotA<T> = T extends LocKey ? never : T;
type NotB<T> = LocKey extends T ? never : T;
export type NotLocKey<T> = NotA<T> & NotB<T>;
function DemandsNonLocKeys<T extends string>({ title, text }: {
title: NotLocKey<T>,
text?: NotLocKey<T>
}) {
return <>{text}: {title}</>;
};
<DemandsNonLocKeys title={"illegal"} text={"!"}/>; // fails, as wanted 🤠
<DemandsNonLocKeys title={"not"} text={"forbidden"}/>; // fails, as wanted 🤠
<DemandsNonLocKeys title={"anything"} text={"goes"}/>; // all non-LocKey: ok!
ReservedNames
if it helps ..public
function that takes such a string.