Typescript negative type check

前端 未结 3 1905
故里飘歌
故里飘歌 2021-01-12 10:27

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?

3条回答
  •  失恋的感觉
    2021-01-12 11:12

    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!
    

提交回复
热议问题