Issue
Is it possible to create a Type
with value in it.
eg:
type Animal = {
kind : "animal"
Legs : number,
CanFly: boolean
}
const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients has to initialize the same value `kind : "animal"`
I would to create an attribute called kind and use that to infer the object and make decisions. However, in the next line, i would expect the clients to pass the same value back in all the initializations. Otherwisem TS compiler would complain `Property 'kind' is missing in type'.
Is there a way to default it without the clients have to pass it back?
Solution
You can create a factory method:
type Animal = {
kind : "animal"
Legs : number,
CanFly: boolean
}
function createAnimal(parameter: Omit<Animal, 'kind'>): Animal {
return {
kind: 'animal',
...parameter,
};
}
const monkey = createAnimal({ Legs: 4, CanFly: false});
Answered By - HTN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.