#Narrow union type in function that spreads same property?

11 messages · Page 1 of 1 (latest)

cerulean citrusBOT
#

@steady parcel Here's a shortened URL of your playground link! You can remove the full link from your message.

andy.ray#0

Preview:```ts
type Node1 = {
x: string
data: {same: string; y: string}
}
type Node2 = {
x: string
data: {same: string; z: string}
}

type MyNode = Node1 | Node2

const nodel = (n: MyNode): MyNode => ({
...n,
data: {
...n.data,
same: "setme"
...```

steady parcel
#

Claude got something right for once!

const nodel = <T extends MyNode>(n: T): T => ({
    ...n,
    data: {
        ...n.data,
        same: 'setme'
    }
})
drowsy hull
#

@steady parcel are you able to change the types? if you rewrite MyNode like this (which is equivalent in terms of allowed values) it works:

cerulean citrusBOT
#
mkantor#0

Preview:```ts
type MyNode = {
x: string
data:
| {same: string; y: string}
| {same: string; z: string}
}

const nodel = (n: MyNode): MyNode => ({
...n,
data: {
...n.data,
same: "setme",
},
})```

drowsy hull
cerulean citrusBOT
#
mkantor#0

Preview:ts ... const mySpecificNode = { x: '', data: { same: 'some very specific string', y: '' }} as const const result = nodel(mySpecificNode) const sus: 'some very specific string' = result.data.same // this typechecks console.log(sus) // but the value is actually `'setme'` at runtime

scenic snow
#

This works

cerulean citrusBOT
#
alpacadev#0

Preview:```ts
type Node1 = {
x: string
data: {same: string; y: string}
}
type Node2 = {
x: string
data: {same: string; z: string}
}

type MyNode = Node1 | Node2

const nodel = <T extends MyNode>(n: T): T => {
return {
...n,
data: {
...n.data,
same: "setme
...```

drowsy hull
scenic snow
#

Ohh you're right, completely missed that between the colorful playground embeds :D