microsoft / microsoft/TypeScript

Suggestion: Allow getters to have predicate return types

未关闭
#43,368 14 条评论 84 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

Suggestion

🔍 Search Terms

getter, predicate, type guard

✅ Viability Checklist

My suggestion meets these guidelines:

  • [✅] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [✅] This wouldn't change the runtime behavior of existing JavaScript code
  • [✅] This could be implemented without emitting different JS based on the types of the expressions
  • [✅] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • [✅] This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

This has been requested before (e.g., #6994) but declined because at the time getters were merely an aspect of implementation. Since that is no longer the case, would there be any interest in revisiting the suggestion?

📃 Motivating Example

class Person {
    name?: string;
}

class Thing {
    constructor(public owner: Person | null = null) {}

    get isOwned(): this is Owned<this> {
      return !!this.owner;
    }
}

type Owned<T extends Thing> = T & { owner: NonNullable<T['owner']> };

💻 Use Cases

I have a use case much like the above. Currently type narrowing by checking thing.owner isn't honored when thing is used as a function argument:

function doSomethingWithOwnedThing(ownedThing: Owned<Thing>) {}

declare const thing: Thing;

if (thing.owner) {
    thing.owner.name; // ok
    doSomethingWithOwnedThing(thing); // not ok (thing.owner is possibly `null`)
}

With the above, I can create a normal function or method that returns a type predicate or otherwise simply assert that thing is an Owned<Thing>. Given that user-defined type guards are encapsulated type assertions, and getters are shiny and neat, a boolean getter that doubles as a type guard would be nicest.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先查看 issue 中的 getter 和 type guard 示例,然后对比 #6994 中之前的讨论以及 #43036 中链接的设计讨论。当提出的 getter 返回类型被接受,并且演示的 Owned<Thing> narrowing 能够在不改变生成的 JavaScript 的情况下正常工作时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
冷清
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。