javascript 我们如何强制Typescript在这里使用默认的泛型参数类型?

lstz6jyr  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(128)
const EventKeys = {
  openItem: 'openItem',
  changeActiveItem: 'changeActiveItem',
  selectionToggled: 'selectionToggled',
} as const

type EventKeys = keyof typeof EventKeys

class Test<Evmt>{

    subscribe<CurrentEeventKey = Evmt>(arg:CurrentEeventKey){
      //here the type is being picked up correctly
      console.log(arg)
      return arg
            //     ^?

  }
}

const t1 = new Test<EventKeys>
//     ^?const t1: Test<"openItem" | "changeActiveItem" | "selectionToggled">

const abc = t1.subscribe('11223')
// here the type param should give error since it should take up constructor value here
//     ^? const abc: "11223"

t1.subscribe<'11223'>('11223')
// but here the type param should not give error since it should take the supplied value here

我试着传递参数并设置默认值,我想让函数从构造函数调用传递的默认值中获取泛型类型值,这样就不需要再定义它了,但是在函数调用中提供时,它应该采用该类型,函数内部的推理是有效的,类型是正确的

1l5u6lss

1l5u6lss1#

使用两个重载,
一个默认值,具有继承的参数一个没有泛型推理,默认为void Playground

import { F } from 'ts-toolbelt'
class Test<Evmt>{
    subscribe<CurrentEeventKey extends Evmt>(arg: CurrentEeventKey): CurrentEeventKey;
    subscribe<CurrentEeventKey = void>(arg: F.NoInfer<CurrentEeventKey>): CurrentEeventKey;
    subscribe<CurrentEeventKey = Evmt>(arg: CurrentEeventKey) {
        //here the type is being picked up correctly
        console.log(arg)
        return arg
        //     ^?
    }
}

相关问题