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:
- Avoid re-writing an interface and manually setting all attributes to optional.
- Avoid assignment of unexpected attributes (such as spelling mistakes).
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…