#Subset of object

21 messages · Page 1 of 1 (latest)

remote marten
#

How can I effectively take only few arguments from parent object?

interface A {
    id: number;
    title: string;
    description: string;
}

interface B extends Omit<A , 'id'> {}

const a: A = {
    title: "",
    description: "",
    id: 0,
}

const b: B = {...a}; // attribute 'id' is also included in object 'b' even it's not in interface B.

I don't want to pick attributes manually.
And the second question, why assigning for object b is valid though id is not in interface B and b contains this attr in the end? I expected that only title and description will be present in this object. Thanks

elfin granite
#

And the second question, why assigning for object b is valid though id is not in interface B and b contains this attr in the end?
that is by design

#

TypeScript uses a structural type system

#

meaning you describe the general shape an object has to have to be of this kind

#

"If it walks like a duck and it quacks like a duck, then it must be a duck"

#

and since Bs only require a title and a description, all As are Bs

#

@remote marten

#

How can I effectively take only few arguments from parent object?
I don't want to pick attributes manually.
good question

#

you could do it manually by using object destructuring

#

like so

feral tundraBOT
#
Ascor8522#7606

Preview:```ts
interface A {
id: number
title: string
description: string
}

interface B extends Omit<A, "id"> {}

const a: A = {
title: "",
description: "",
id: 0,
}

const {id, ...b} = a```

elfin granite
#

!ts id b

feral tundraBOT
#
(property) A.id: number /* 2:5, 12:5 */
const id: number /* 15:9 */``````ts
const b: {
    title: string;
    description: string;
} /* 15:16 */```
elfin granite
#

maybe having a function and a list of all the keys would help

#

you could then loop over the obejct and chose what keys to copy

remote marten
#

so there isn't any way that TS will do it for me just by defined interface right

elfin granite
#

no

#

interfaces and types don't exist at runtime

#

they are simply removed, and don't change the code you write

#

the JS you write is the JS that is executed

#

the TS types are only there to help the compiler check your code