Warum können „void' und „{}' nicht als „never type' in TypeScript abgeleitet werden?
P粉548512637
P粉548512637 2023-09-04 16:03:52
0
1
573
<p>Ich erhalte unterschiedliche Ergebnisse, wenn ich den void-Typ von TypeScript mit Kreuztypen mit anderen Typen verwende. </p> <pre class="brush:php;toolbar:false;">type A = void & // A ist void & Typ B = void & '1' // B ist nie Typ C = void & // C ist nie Typ D = void & string // D ist nie Typ E = void & String // E ist void & String</pre> <pre class="brush:php;toolbar:false;">type A = void & Typ E = void & String</pre> <p>Sie sollten auch vom Typ nie sein, oder? </p>
P粉548512637
P粉548512637

Antworte allen(1)
P粉285587590

{}String 都是对象类型,而 string'1' 都是原始类型。你可以将 void 与对象类型相交,因为对象类型通过添加属性来相交:

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

相反,原始类型通过减少可能的值集合来相交:

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

而通过将原始类型与对象类型相交,你可以为原始类型添加新属性:

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

但是一个原始类型永远不能成为另一个原始类型。因此,相交两个不同的原始类型将导致 never

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

最后,void 是一个原始类型。


所以,这意味着 void & { foo: number } 意味着原始类型 void 也将具有属性 foo

然而,void & string 将产生 never,因为它们是两种不同的原始类型。

但是,void & Stringvoid 加上 String 的属性,因为 String 是一个对象类型(通过 new String() 创建)。


然而,这一切都没有什么意义。你不能给 void 分配除了 undefined 之外的任何东西,而 undefined 不能有属性。所以我认为在你的代码库中 void & Type 没有存在的理由。如果你认为你需要它,我会问你为什么需要它,并尝试重构代码以不需要它。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!