Typescript是否支持“子集类型"? [英] Does Typescript support "subset types"?

查看:220
本文介绍了Typescript是否支持“子集类型"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个界面:

interface IUser {
  email: string;
  id: number;
  phone: string;
};

然后我有一个函数,需要该类型的子集(或完全匹配).也许它将传递整个对象,使其仅通过{email: "t@g.com"}传递.我希望类型检查器同时允许两者.

Then I have a function that expects a subset (or complete match) of that type. Maybe it will pass an entire object, made it will just pass in {email: "t@g.com"}. I want the type checker to allow for both.

示例:

function updateUser(user: IUser) {
  // Update a "subset" of user attributes:
  $http.put("/users/update", user);
}

Typescript是否支持这种行为?我发现它非常有用,尤其是对于Redux这样的范例.

Does Typescript support this sort of behavior yet? I could find it very useful, particularly with paradigms like Redux.

为了澄清,目标是:

  1. 避免重写接口,并将所有属性手动设置为可选.
  2. 避免分配意外属性(例如拼写错误).
  3. 避免使用诸如if语句之类的命令性逻辑,这些命令会失去编译时类型检查的好处.
  1. Avoid re-writing an interface and manually setting all attributes to optional.
  2. Avoid assignment of unexpected attributes (such as spelling mistakes).
  3. Avoid imperative logic such as if statements, which forfeit benefits of compile time type checking.

更新:Typescript宣布支持映射类型发布后应该可以解决此问题.

UPDATE: Typescript has announced support for mapped types which should solve this problem once published.

推荐答案

Typescript现在支持部分类型.

Typescript now supports partial types.

创建部分类型的正确方法是:

The correct way to create a partial type is:

type PartialUser = Partial<IUser>;

这篇关于Typescript是否支持“子集类型"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆