Is it possible to narrow the type of n.data here?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
11 messages · Page 1 of 1 (latest)
Is it possible to narrow the type of n.data here?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@steady parcel Here's a shortened URL of your playground link! You can remove the full link from your message.
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"
...```
Claude got something right for once!
const nodel = <T extends MyNode>(n: T): T => ({
...n,
data: {
...n.data,
same: 'setme'
}
})
@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:
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",
},
})```
eh, this is kinda fishy. here's an example of why it's not safe:
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
This works
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
...```
that's the same as what they posted above (via Claude)
Ohh you're right, completely missed that between the colorful playground embeds :D