Why can't void and {} be inferred as never type in TypeScript?
P粉548512637
P粉548512637 2023-09-04 16:03:52
0
1
587
<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粉548512637
P粉548512637

reply all(1)
P粉285587590

{} 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!