gpt4 book ai didi

TypeScript:将可调用类型声明为类方法类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:40 25 4
gpt4 key购买 nike

我有一个可调用的类型别名或接口(interface),例如

type MyCallable = (n: number) => string

然后我有一个类,其中一个方法属于可调用类型:

class MyClass {
myMethod(n: number): string {
return ''
}
}

我想改为使用 MyCallable 类型来声明它的类型:

class MyClass {
myMethod(n): MyCallable {
return ''
}
}

显然这种方法不起作用,因为 myMethod 不会返回 MyCallable,而是 本身一个 MyCallable

这在 TS 中甚至可能吗?

最佳答案

一个稍微罗嗦的方式是声明和实现一个接口(interface):

type MyCallable = (n: number) => string

type WithCallable = {
myMethod: MyCallable
}
class MyClass implements WithCallable {
myMethod(n) {
return ''
}
}

关于TypeScript:将可调用类型声明为类方法类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56385324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com