#How can I make return type be inferred from generic type?

3 messages · Page 1 of 1 (latest)

merry dock
#

I have the following type:

type ExecuteParam<K extends keyof HTMLElementTagNameMap> = {
    tags: K[]
}

and the following class:

class Builder<K extends keyof HTMLElementTagNameMap> {
    private tags: K[] = []

    private constructor() { }
    
    static create() {      
      return new this()    
    }

    tag(...tags: K[]) {
      this.tags = tags      
      return this    
    }

    build(): ExecuteParam<K> {
      return { tags: this.tags } 
    }
}

The problem is that, currently the below code, is inferred as ExecuteParam<keyof HTMLElementTagNameMap>:

const result = Builder
  .create()
  .tag('a')
  .build()

// inferred as ExecuteParam<keyof HTMLElementTagNameMap>

How can I make the result of Builder.build() here be inferred as ExecuteParam<'a'> ?

vestal pagoda
#

i think the only way is if you return a new Builder from tag which has its own generic parameter
because changing K isnt possible
(...tags: T): this is Builder<T> { doesnt work either with a return type

sharp charm
#

yeah, you need something like this: