Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

interface - Does Typescript support "subset types"?

Let's say I have an interface:

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

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: "[email protected]"}. I want the type checker to allow for both.

Example:

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

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

To clarify, the goal is:

  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.

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

question from:https://stackoverflow.com/questions/36871057/does-typescript-support-subset-types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Typescript now supports partial types.

The correct way to create a partial type is:

type PartialUser = Partial<IUser>;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...