Reputation: 1591
I'm trying to explicitly type a const which is created using a rest param in a destructured object. I can see that typescript can infer that it will have all the properties of the type of the source object, less any properties which I create separate consts for. But, I have a predefined type which I specifically want to use for my new const. Is this possible?
interface Animal {
name: string,
species: string,
legs: number,
tail: boolean,
alive: boolean,
}
// say we know an animal is alive and therefore want a type without this property
// (yes, we could extend Animal with alive: true, but this a contrived example, go with it)
type LivingAnimal = Omit<Animal, 'alive'>
// dave is an Animal, but we want a LivingAnimal type from him, which omits the 'alive' property
const dave: Animal = {
name: 'Dave',
species: 'lizard',
legs: 4,
tail: true,
alive: true,
}
// with object destructuring, I can infer that alive is a boolean and daveAnimal is the same type as LivingAnimal (ie has all the same props as Animal except alive)
// But what I actually *want* to achieve is to type daveAnimal specifically as LivingAnimal
const {alive, ...daveAnimal} = dave;
// but when I try and do this, it fails
const {alive2, ...daveAnimal2}: {alive2: string, ...daveAnimal2: LivingAnimal} = dave;
// so is there a way of specifying a predefined type for the animal const, created with a rest param in a destructured object?
Here is the code in the typescript playground.
I have done some googling and read articles like this one and other SO questions like this one but they don't quite cover my use of rest params, or at least not in a way which I've understood.
I hope I've explained what I'm trying to achieve adequately. It's not terribly important - in practice I can work with what I've already got, it's more for neatness and advancing my understanding. Thanks for any wisdom you can share.
Upvotes: 0
Views: 105