Skip to content
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

Make WeakSet.has() and WeakMap.has() accept unknown and assert type. #180

Open
DeepDoge opened this issue Jan 1, 2024 · 1 comment
Open

Comments

@DeepDoge
Copy link

DeepDoge commented Jan 1, 2024

It's annoying when you have a value with unknown type and can't use it inside .has() or .delete() function. Which doesn't make sense at all. unknown should be allowed and also .has() should assert type.

Solution:

interface WeakSet<T extends WeakKey> {
    delete<V>(value: V & (unknown extends V ? unknown : T)): value is T
    has<V>(value: V & (unknown extends V ? unknown : T)): value is T
}

Result:

interface Foo {
    foo: string
}

interface Bar {
    bar: string
}

const foo: Foo = { foo: "foo" }
const bar: Bar = { bar: "bar" }

const unknownFoo: unknown = foo satisfies Foo

const fooSet = new WeakSet<Foo>()

if (fooSet.has(unknownFoo)) {
    unknownFoo.foo // Foo
}

if (fooSet.has(foo)) {
    foo.foo // Foo
}

if (fooSet.has(bar)) { // Error: No overload matches this call.
    bar.foo // Foo
}

Same thing can be done for the WeakMap

@russelldavis
Copy link

The type predicates in these definitions are unsafe, see #125 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants