Open fregante opened 2 years ago
I think it could be useful.
If only TS had negated types: https://github.com/microsoft/TypeScript/pull/29317
I can't make it work as a reusable type:
type Not<Yes, Not> = Yes extends Not ? never : Yes;
type NotHello = Not<string, 'hello'>;
const notHello: NotHello = 'hello';
// No error because `NotHello === string`
It's possible that TypeScript "forgets" the negation too early
The generic-based works but it's buggy with variables:
type Not<Yes, Not> = Yes extends Not ? never : Yes;
type NotHello<S extends string> = Not<S, 'hello'>;
export const join = <S extends string>(
...parts: Array<NotHello<S> | number>
): string => parts.join(',');
join('hello'); // Error 🎉
join('hello', 'world'); // Error 🎉
let nonConstString = 'sup'
join('hello', nonConstString); // No error 😰
The generic-based works but it's buggy with variables
They needs to be as const
or types will be widened.
Checkout the following code on TS Playground:
type Not<Yes, Not> = Yes extends Not ? never : Yes;
type NotHello<S extends string> = Not<S, 'hello'>;
export const join = <S extends string>(
...parts: Array<NotHello<S> | number>
): string => parts.join(',');
join('hello'); // Error 🎉
join('hello', 'world'); // Error 🎉
let nonConstString = 'sup' as const
join('hello', nonConstString); // Error 🎉
Could microsoft/TypeScript#51865 help solve this issue?
I was looking for a way to implement “any string that doesn’t start with a slash” with template literals, then I realized that it can be achieved with a generic
Not
type:Is there anything like
Not
?Edit: related:
Upvote & Fund