Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript negative type check

Tags:

typescript

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?

like image 556
WHITECOLOR Avatar asked Sep 05 '16 10:09

WHITECOLOR


1 Answers

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!
like image 82
Karol Majewski Avatar answered Oct 10 '22 01:10

Karol Majewski