When working with TypeScript, it's important to remember that it is a structurally-typed language. This means that when you create a `type` or `interface`, you are defining a specific shape that other objects must adhere to. It's worth noting that assigning defaults within TypeScript types is not supported.
type Animal = {
kind : "animal"
Legs : number,
CanFly: boolean
}
If your type definition includes properties like `kind: "animal"` as a string literal type, this indicates that only that exact value can be assigned to it. In this case, any object created using the `Animal` shape must have `kind: "animal"` specified.
To implement discriminated unions in TypeScript, you could consider creating more specific types instead of a generic one such as 'Animal'. For instance:
type Snake = {
kind: "snake"
Legs : number,
CanFly: boolean
}
type Dolphin = {
kind: "dolphin",
Legs: number,
CanFly: boolean
}
type Monkey = {
kind: "monkey",
Legs: number,
CanFly: boolean
}
These specific types can then be used to create a discriminated union like so:
type Animal = Snake | Dolphin | Monkey
To summarize, TypeScript focuses on defining shapes rather than providing default values within type declarations. If an object does not align with a specific shape defined by a TypeScript type, it cannot be considered as that type.