#valid generic manipulation helping

15 messages · Page 1 of 1 (latest)

foggy latch
#

I cant find a proper way to define a class with generics so that i can implement method add as in the ts playground link below.

class X: I may understand that it may be cause index 'a' might not be a valid index?
class Y: dont really know
class Z: all good
class G: just another try to have it working but it says that "number is not assignable"?

hushed fractalBOT
#
andreaelektronvolt#0

Preview:```ts
class X<T extends Record<string, unknown> {

constructor(public val: T) {

}
add() {
this.val['a'] = 1;
}
}

class Y<T extends {[k in (string | 'a')]: any}> {
constructor(public val: T) {

}
add() {
this.val['a'] = 1;
}
}

class Z<T extends {a: any}> {
...```

ebon grail
#

What is it that you are trying to do?

#

Is add supposed to always set val.a to 1?

foggy latch
#

my current real class is similar to G

#

i would expect G.add to be working

#

as m should be a valid key in T

#

no?

hushed fractalBOT
#
nonspicyburrito#0

Preview:```ts
class G<T extends Record<string, number>> {
constructor(public val: T) {}

add(m: keyof T) {
this.val[m] = 1
}
}

const g = new G({foo: 42 as const})
// ^?

g.add("foo")

g.val.foo
// ^?```

ebon grail
#

Here's a demonstration why that's not allowed.

#

g is G<{ foo: 42 }>, but after calling g.add('foo') the value gets changed to 1, which no longer matches the type.

foggy latch
#

hmm

#

now i get it

ebon grail
#

If you instead rewrite it into:

class G<K extends string> {
    constructor(public val: Record<K, number>) {}

    add(m: K) {
        this.val[m] = 1
    }
}

Then it will work.

foggy latch
#

gotcha