#Why is this code failing? Even if there are two separate types, they should be identical.

33 messages ยท Page 1 of 1 (latest)

valid nexusBOT
#
hornta#4659

Preview:```ts
interface A {
a: string | null
}

type AWithAAsString = Omit<A, "a"> & {a: string}

const theFunc = (a: AWithAAsString) => {}

const obj: A = {a: ""}

if (obj.a !== null) {
theFunc(obj)
}```

neon tiger
#

I've narrowed it down as much as I can from my code real code.

floral crater
#

@neon tiger A.a may be null

#

wait

#

yeah idk typescript is just being funny

#

because this works

valid nexusBOT
#
n_n#2622

Preview:ts ... if (obj.a !== null) { theFunc({a: obj.a}) } ...

zinc lynx
#

typescript doesn't really narrow obj when you check obj.a. the only time it does that is when obj is a discriminated union and a is a discriminant property. it's confusing though because direct accesses of obj.a are narrowed within the scope, even though obj as a whole isn't

#

i feel like the latter thing didn't used to happen, but i may have just not run across it until like a month or two ago when it confused me as well

floral crater
#

it's kinda silly how spread doesn't retain the narrowed types :(

floral crater
neon tiger
zinc lynx
#

(unless the reasoning for these semantics have something to do with obj.a possibly being mutated later? hmm...)

zinc lynx
floral crater
zinc lynx
#

i guess, but there'd need to be a special rule to allow the assignment of a non-string to obj.a in the first place

#

obj would be "{ a: string } when read but { a: string | null } for write purposes"

floral crater
#

you mean if obj as a whole was narrowed by default?

zinc lynx
#

yeah

#

my last message was written badly, revised now to actually make sense

floral crater
#

maybe it's performance concerns in the case of deeply nested narrowing...

#

but also if your narrowing is deeply nested wyd tbh

zinc lynx
#

yeah, and maybe some of the machinery is already there for setters and getters? i don't remember if they allow different types for input/output (i never really use them)

floral crater
floral crater
zinc lynx
#

ah yeah obj.x = obj.x potentially not working sounds gross

floral crater
#

lol

zinc lynx
#

i'm running away back to my purely-functional safe space where i don't have to think about stuff like this

floral crater
#

is it really functional enough if it's not pointfree ๐ŸšŽ

zinc lynx
#

that's what pipe is for!