#Static generic with this strange behavior

12 messages · Page 1 of 1 (latest)

high minnowBOT
#
andreaelektronvolt#0

Preview:```ts
export abstract class Base {
static encode<T extends typeof Base>(
this: T,
x: InstanceType<T>,
buf: Uint8Array
): number {
throw new Error("stub!")
}
}
export class Sub extends Base {
keys!: string

static encode(
this: Sub,
x: InstanceType<typeof Sub>,
bytes: Uint8Array
): number {
return 1
}
}
...```

cinder coral
#
Class static side 'typeof Sub' incorrectly extends base class static side 'typeof Base'.
  Types of property 'encode' are incompatible.
    Type '(this: Sub, x: Sub, bytes: Uint8Array<ArrayBufferLike>) => number' is not assignable to type '<T extends typeof Base>(this: T, x: InstanceType<T>, buf: Uint8Array<ArrayBufferLike>) => number'.
      The 'this' types of each signature are incompatible.
        Type 'T' is not assignable to type 'Sub'.
          Property 'keys' is missing in type 'typeof Base' but required in type 'Sub'.
#

probably something strange here

#

if i remove the encode method i can obviously call Sub.encode(...) and have typescript properly infer/validate

#

But in one case i need one of the sub classes to Override encode

#

and i dont seem to be able to find the proper way

solemn ravine
#

Sub is a subclass of Base, which means that every valid operation you can do on Base has to also be valid with Sub.

#

In your code, you can call Base.encode on many kinds of T, but you can only call Sub.encode on only one kind of T (Sub).

#

I'm not sure why encode has to be a static method, it makes a lot more sense for it to be an instance method, and have Base#encode to be abstract.

cinder coral
#

hey burrito you're right about havign at a method aqnd it is also like that as well. but for other reason i need to also hve it as a static method

#

Thanks for the explanation

wanton pagoda