Skip to content

How should one check for compSig instanceof Signal for a computed after #587? #613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AlexJeffcott opened this issue Oct 14, 2024 · 3 comments
Labels
question Further information is requested

Comments

@AlexJeffcott
Copy link

AlexJeffcott commented Oct 14, 2024

I would like to check to see whether a variable is a computed. I previously did this using instanceof Signal which was good enough for my purposes.

Since upgrading preact/signals this no longer works as ReadonlySignal no longer extends Signal.

This is the change in question.

This is the sort of code I wrote.

getValue(computedOrValue: ReadonlySignal<V> | V): N {
  if (computedOrValue instanceof Signal) { \\ checks is a Signal/Computed
    return computedOrValue.value
  } else {
    return computedOrValue
  }
}

This is the sort of code I would like to be able to write.

getValue(computedOrValue: ReadonlySignal<V> | V): N {
  if (computedOrValue instanceof ReadonlySignal) { \\ can check is a Computed
    return computedOrValue.value
  } else {
    return computedOrValue
  }
}
@XantreDev
Copy link
Contributor

XantreDev commented Oct 14, 2024

I think you could do it like this

const Computed = computed(() => null).prototype

if (a instanceof Computed) {}

More future proof solution

if (a?.brand === Symbol.for("preact-signals")) {} // true for any Signal and ReadonlySignal

@XantreDev
Copy link
Contributor

But actually under the hood ReadonlySignal still extends Signal and if you check it instanceof Signal it will return true with ReadonlySignal

@JoviDeCroock
Copy link
Member

Exactly this change is only on a types level and does not affect any runtime, the type narrowing is just a bit broken in TypeScript it feels like.

@rschristian rschristian added the question Further information is requested label Oct 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants