Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 从其父对象推断方法类型_Typescript - Fatal编程技术网

Typescript 从其父对象推断方法类型

Typescript 从其父对象推断方法类型,typescript,Typescript,我有一个对象类型,它可以有它想要的任何属性,但它的属性之一必须是函数(如果定义的话)。问题是:我希望此函数类型包含所有其他属性作为其参数。看,以便更好地理解 // https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546 type NoInfer<T> = [T][T extends any ? 0 : never]; type Indexable = { [key: string

我有一个对象类型,它可以有它想要的任何属性,但它的属性之一必须是函数(如果定义的话)。问题是:我希望此函数类型包含所有其他属性作为其参数。看,以便更好地理解

// https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546
type NoInfer<T> = [T][T extends any ? 0 : never];

type Indexable = {
    [key: string]: any
}

type Events<T extends Indexable = Indexable> = {
    onFoo?: (arg: Omit<T, keyof Events>) => void
}

type Foo<T extends Indexable> = T & Events<NoInfer<T>>

declare function test<T extends Indexable>(foo: T & Foo<T>): void

test({
    a: 1,
    onFoo(arg) {
        // "typeof arg" should be "{ a: number }"
    }
})
//https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546
类型NoInfer=[T][T扩展任何?0:never];
类型可转位={
[键:字符串]:任何
}
类型事件={
onFoo?:(参数:省略)=>void
}
类型Foo=T&Events
声明函数测试(foo:T&foo):void
试验({
答:1,,
onFoo(arg){
//“typeof arg”应为“{a:number}”
}
})

我想这是循环类型的问题,因为它也不起作用。

我无法让类型推断按您想要的方式工作。无论我做什么,要么
T
无法推断,要么它推断但
onFoo
属性的参数不能正确推断。我可能会认为这不是一个编译器错误和更多的设计限制。可能与
onFoo
参数没有正版相关。这可能与类型推断算法需要做多少才能成功有关。我真的不确定。我知道,当我像这样与编译器抗争时,我通常会输。因此,尝试做一些争议性较小的事情可能是值得的

更直接的方法是使用两个函数参数(我知道您不想这样做),如中所示:

您至少可以使用
makeFoo()
获得所需的推理:

test(
  makeOnFoo({ a: 1 }, arg => {
    console.log(arg.a.toFixed()); // okay
  })
);
我不知道你是否可以接受,但至少它能更好地与编译器配合使用


哦,希望这能有所帮助。祝你好运


blecch,看起来类型推断真的不想这样工作。您是否考虑过让
test()
接受两个参数,一个是
T
类型,另一个是
(arg:T)=>void
?@jcalz我宁愿使用断开的类型,也不愿接受两个参数。也许这是一只虫子?
declare function test<T>(
  foo: T & { onFoo?: (arg: Omit<T, "onFoo">) => void }
): void;
test(
  makeOnFoo({ a: 1 }, arg => {
    console.log(arg.a.toFixed()); // okay
  })
);