Depending on the context and usage, the approach may vary. One way to achieve this is by using a function parameter as shown below:
type StartsWithSlash = `/${string}`;
type OppositeOf<TypeToNarrow, TypeToNegate> = TypeToNarrow extends TypeToNegate ? never : TypeToNarrow;
function example<T extends string>(param: OppositeOf<T, StartsWithSlash>) {
console.log(param);
}
example("works");
example("/fails"); // <== Error as desired
It's important to note that this method is only effective with arguments that have literal types. In the example below, there is no error because TypeScript infers the type of str
as string
.
let str = "/should-fail-but-doesn't";
example(str); // <== No error
Playground link
This method is suitable for defining types for function parameters, although its applicability is quite limited and specific. It may not be a viable solution for more general use cases.
A related question explores a different approach using a branded type, which could be a more reliable solution based on the specific requirements.