Home  >  Q&A  >  body text

Why can't void and {} be inferred as never type in TypeScript?

<p>I get different results when I use TypeScript's void type with other types using cross types. </p> <pre class="brush:php;toolbar:false;">type A = void & {} // A is void & {} type B = void & '1' // B is never type C = void & 1 // C is never type D = void & string // D is never type E = void & String // E is void & String</pre> <pre class="brush:php;toolbar:false;">type A = void & {} type E = void & String</pre> <p>They should also be of type never, right? </p>
P粉548512637P粉548512637381 days ago574

reply all(1)I'll reply

  • P粉285587590

    P粉2855875902023-09-05 12:01:48

    {} and String are both object types, while string and '1' are both primitive types. You can intersect void with object types because object types intersect by adding properties:

    type A = { foo: number } & { bar: string } // { foo: number, bar: string }

    In contrast, primitive types intersect by reducing the set of possible values:

    type B = string & 'abc' // 'abc'

    And by intersecting a primitive type with an object type, you can add new properties to the primitive type:

    type C = string & { foo: number }
    declare const c: C
    c.foo // number

    But a primitive type can never become another primitive type. Therefore, intersecting two different primitive types will result in never

    type D = string & number // never
    type E = 1 & 2 // never

    Finally, void is a primitive type.


    So, this means void & { foo: number } means that the primitive type void will also have the attribute foo.

    However, void & string will produce never since they are two different primitive types.

    However, void & String are properties of void plus String, because String is an object type (via new String() Create).


    However, all this means nothing. You cannot assign void to anything other than undefined, and undefined cannot have properties. So I think void & Type has no reason to exist in your codebase. If you think you need it, I would ask you why you need it and try to refactor the code so that it doesn't need it.

    reply
    0
  • Cancelreply