我正在尝试创建一个带有两个参数的函数,第一个是类引用,第二个是只有一个参数的函数,该参数是类引用的实例,输出是特定类型。 我尝试了下面的代码,但打字稿告诉我p的类型未知,即使我希望p是Pair的实例。
interface Point{
x: number
y: number
}
class Pair{
key = 0
value = 0
}
function set<Class extends { new (): Type }, Type>(
inputClass: Class,
constructor: (o: Type) => Point) {
//implementation...
}
set(Pair, p => ({x: p.key, y: p.value}))
// Typescript says:
// (parameter) p: unknown
// Object is of type 'unknown'.(2571)
我希望打字稿知道p必须是Pair的实例
我能够使用Java泛型来实现,但是我仍然无法在打字稿中进行复制。遵循代码:
public <K extends Pair, T extends Class<K>> void setRenderer(T classe, Function<K, Point> constructor){
//implementation
}
答案 0 :(得分:2)
这应该有效:
function set<C>(
inputClass: new ()=>C,
constructor: (o: C) => Point) {
//implementation...
}
答案 1 :(得分:1)
泛型不能像这样工作,类型推论不会这样。
简单的解决方案:
interface Point{
x: number
y: number
}
class Pair{
key = 0
value = 0
}
declare function set<Type>(constructor: (o: Type) => Point): void;
set<Pair>(p => ({ x: p.key, y: p.value }))
或者如果您真的想通过课程:
interface Point{
x: number
y: number
}
class Pair{
key = 0
value = 0
}
function set<Type>(
inputClass: { new (): Type },
constructor: (o: Type) => Point) {
//implementation...
}
set(Pair, p => ({ x: p.key, y: p.value }))
答案 2 :(得分:0)
我不确定为什么在这里需要上课。
您可以通过界面实现所需的内容,例如:
interface Point{
x: number
y: number
}
interface Pair{
key:number
value:number
}
const instance: Pair = {
key : 0,
value : 0
}
function set(value: Pair):Point {
return ({x: value.key, y: value.value})
}
或者如果您确实想要课程,可以执行以下操作: