In typescript: is it possible to check if type expected type IS NOT some type? Or create an interface that defines methods/props that should not be there?
Disallowing specific properties
Use the never
type to tell TypeScript a property should not exist on an object.
interface Nameless extends Object {
name?: never;
}
Usage:
declare function foo<T extends Nameless>(argument: T): void;
foo(document); // OK
foo(1); // OK
foo({ name: 'Bob' }); // Error
Negating object types
Use the Subtract
helper:
type Subtract<T, U> = T & Exclude<T, U>
Usage:
declare function process<T>(argument: Subtract<T, Window>): void;
process(1) // OK
process({}) // OK
process(window) // Error
Negating literals
Use the Subtract
helper again:
type Subtract<T, U> = T & Exclude<T, U>
Usage:
type Insult =
| 'You silly sod!'
| 'You son of a motherless goat!';
declare function greet<T extends string>(greeting: Subtract<T, Insult>): void;
greet('Hello, good sir!'); // OK
greet('You silly sod!'); // Error!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With