#Type information lost when destructuring object.

8 messages · Page 1 of 1 (latest)

bitter iron
#

I am trying to extend an object with some added properties but I cannot for the life of me understand why this doesn't work.

export function foo() {
    const record = fetchDynamoRecord() // record: { foo: "bar" } & dynamoose.Item
    return record
}

export function bar() {
    const record = fetchDynamoRecord() // record: { foo: "bar" } & dynamoose.Item
    return {
        ...record,
        someFn: () => "hello, world!"
    }
}


const A = foo() // correct type inference { foo: "bar" } & dynamoose.Item 
const B = bar() // incorrect type inference. { foo: "bar" } & Partial<dynamoose.Item> missing *some* properties of dynamoose.Item 
pine mistBOT
#
kcin420#0

Preview:```ts
import {model, Schema} from "dynamoose"
import {Item} from "dynamoose/dist/Item"

const schema = new Schema({
name: {
type: String,
},
age: {
type: Number,
},
occupation: {
type: String,
},
})

type Model = {
name: string
age: number
...```

bitter iron
#

these are the only properties being inferred from the dynamoose.Item type.

conformToSchema: () => ...,
toDynamo: () => ...
modern creek
#

@bitter iron When you spread a class instance, the methods are lost:

pine mistBOT
#
class Foo {
  x = 0;
  method() { return "bar"; }
}

const f = new Foo();
//    ^? - const f: Foo
const f2 = { ...f }
//    ^? - const f2: {
//        x: number;
//    }
modern creek
#

This is accurate to the runtime behavior: f2.x is 0, but f2.method is undefined.

#

{ ...obj, newProperty: 0 } is a good way to add a new property to a plain object, but if you're dealing with a class instance, you're probably better to use Object.assign... though this does change the original object, too

pine mistBOT
#
retsam19#0

Preview:```ts
import {model, Schema} from "dynamoose"
import {Item} from "dynamoose/dist/Item"

const schema = new Schema({
name: {
type: String,
},
age: {
type: Number,
},
occupation: {
type: String,
},
})

type Model = {
name: string
age: number
...```