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?
TypeScript is a structurally-typed language. Meaning when you defined a type or interface you defined a shape other objects must conform to. And assigning defaults within TS types is not possible.
type Animal = {
kind : "animal"
Legs : number,
CanFly: boolean
}
I assume you are on a recent version of TS since your kind is a string literal type, "animal", and it can only ever be that string literal. And you have to supply kind: "animal" when you create objects of Animal shape.
Now, if you want to implement discriminated unions, you might choose the following approach (perhaps animal is a little to generic in this case):
type Snake = {
kind: "snake"
Legs : number,
CanFly: boolean
}
type Dolphin = {
kind: "dolphin",
Legs: number,
CanFly: boolean
}
type Monkey = {
kind: "monkey",
Legs: number,
CanFly: boolean
}
Then a discriminated union:
type Animal = Snake | Dolphin | Monkey
To reiterate, TS does not support defaults in a type declaration. TS types define the shapes of things and if an object, O, doesn't conform to a shape, T, well then O is not a T.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With