What I need to to define noAge
as being Person
right in the destructure line. As you see I’d like to assign age
to noAge
later:
interface Person{
name: string
age?: number
}
const person: Person = {
name: 'John Doe',
age: 20
};
const {age, ...noAge} = person;
noAge.age = 30; // an error here
It shows the type of noAge
being:
const noAge: {
name: string;
}
but I want it to be Person
.
Everything I tried so far was an error.
Playground
13
I don’t think there’s a way to provide a type annotation for the rest property in a variable declaration using destructuring patterns – at least none for a type including the other properties. The best solution I can suggest is to declare the variables up front, then assign them:
let age: number | undefined, noAge: Person;
({age, ...noAge} = person);
noAge.age = 30;
or just introduce an extra variable:
const {age, ...noAge} = person;
const oldPerson: Person = noAge;
oldPerson.age = 30;
Of course, the idiomatic solution would be to just not use destructuring at all if you want to put a new age
back on the noAge
object, but use an object literal with spread syntax:
const {age} = person;
const oldPerson = {...person, age: 30};
1