TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Misusing TypeScript assertion functions for fun and profit

38 点作者 chriskrycho大约 3 年前

3 条评论

tomduncalf大约 3 年前
Good write-up and it is quite a neat feature. We wanted to use it in the library I work on to model how a method of our class mutates an argument to add new properties to it (IIRC, it was a little while ago), but hit an issue that you need to explicitly type the instance of the class for this to be usable – that is, a user can&#x27;t write &quot;const assertingInstance = new AssertingClass()&quot; but instead has to write &quot;const explicitAssertingInstance: AssertingClass = new AssertingClass()&quot;. We decided that this was going to be too inconvenient for our users, and so pursued a different API direction.<p>I raised an issue and Ryan from the TS team gave a good explanation of why this is so, and why it&#x27;s unlikely to change in the near future (performance penalty of doing the analysis required), but I thought I&#x27;d mention it in case anyone is looking to use this feature and might hit the same issues. The TS issue is <a href="https:&#x2F;&#x2F;github.com&#x2F;microsoft&#x2F;TypeScript&#x2F;issues&#x2F;47945" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;microsoft&#x2F;TypeScript&#x2F;issues&#x2F;47945</a> if you&#x27;d like to see more details.
dgritsko大约 3 年前
I&#x27;m still learning TypeScript and didn&#x27;t know about &quot;assertion signatures&quot; prior to reading this article. They were added in 3.7. For any other TS users who also aren&#x27;t familiar: <a href="https:&#x2F;&#x2F;www.typescriptlang.org&#x2F;docs&#x2F;handbook&#x2F;release-notes&#x2F;typescript-3-7.html#assertion-functions" rel="nofollow">https:&#x2F;&#x2F;www.typescriptlang.org&#x2F;docs&#x2F;handbook&#x2F;release-notes&#x2F;t...</a>
eyelidlessness大约 3 年前
I don’t see how this is an abuse of assertions, it’s just unnecessary mutation and the caveats reveal that. For the specific case of adding a known field, you can return a value with that field added. If you create a new value derived from the old one, you also regain a stable object shape (at the expense of allocation).<p>For the general case of extend, all of the same applies. To avoid `never`, you can use Omit or perhaps Exclude to handle overwritten field types. Applying all of that to this simple extend example:<p><pre><code> function extend&lt;T extends object, U extends object&gt;( value: T, extension: U ): Omit&lt;T, keyof U&gt; &amp; U { return Object.assign(value, extension); } </code></pre> The resulting type may be unwieldy, but you can tame it with a Merge type:<p><pre><code> type Merge&lt;T&gt; = { [K in keyof T]: T[K]; } &#x2F;&#x2F; then change the return type to: &#x2F;&#x2F; Merge&lt;Omit&lt;T, keyof U&gt; &amp; U&gt;</code></pre>
评论 #31278696 未加载