#Why does the compiler think `v: string | null` might be null after `v && v.trim()`?

25 messages ยท Page 1 of 1 (latest)

short hollyBOT
#
bawdyinkslinger#0

Preview:```ts
declare const payload: {
contents: string
name: string
}[]
let content = ""
let onOpen: string | null = null
let onClose: string | null = null

payload.forEach(function (payload, index) {
if (index === 0) {
content = payload.contents
} else {
if (payload.name === "on
...```

ornate swift
#

Why do I get this error message? Shouldn't it be impossible for onOpen to be null there?

#

Neither of those types make sense to me

green flame
#

Ah, this is a classic issue.

ornate swift
#

๐Ÿ™„ Why do I keep running into those?

green flame
#

You need to do let onOpen = null as (string | null);

#

This is a place where the contextual flow typing gets confused.

ornate swift
#

What's happening here?

short hollyBOT
#
bawdyinkslinger#0

Preview:```ts
declare const payload: {
contents: string
name: string
}[]
declare const takeString: (s: string) => void
let content = ""
let onOpen = null as string | null
let onClose = null as string | null

payload.forEach(function (payload, index) {
if (index === 0) {
content = payload.conte
...```

ornate swift
#

do I need an as string to solve this one?

#

This is the real code that creates that error: ```ts
$(document).one(':dialogopened', function () {
$.wiki(onOpen);
});

green flame
#

That code doesn't really make much sense with the extra function wrapping?

ornate swift
#

Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.

green flame
#

This one is more reasonable. TS doesn't narrow (mutable things) across function boundaries.

#

You can 'save' the narrowed value into a constant.

ornate swift
#

I guess I don't really write code like this often. I'm trying to port some code I found in a js library

green flame
#

Yeah, I think most people use a lot of const which avoids the issue

ornate swift
#

Would you do something vastly different?

green flame
#

If you can it may be easier to just move the check inside the event and avoid the issue

#

Not 100% the same, but I'd guess in most cases an event handler that does nothing is basically the same as not setting the event handler at all.