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(argument: T): void;
foo(document); // OK
foo(1); // OK
foo({ name: 'Bob' }); // Error
Negating object types
Use the Subtract
helper:
type Subtract = T & Exclude
Usage:
declare function process(argument: Subtract): void;
process(1) // OK
process({}) // OK
process(window) // Error
Negating literals
Use the Subtract
helper again:
type Subtract = T & Exclude
Usage:
type Insult =
| 'You silly sod!'
| 'You son of a motherless goat!';
declare function greet(greeting: Subtract): void;
greet('Hello, good sir!'); // OK
greet('You silly sod!'); // Error!