简体   繁体   English

扩展打字稿界面+优化功能签名

[英]Extending typescript interfaces + refine function signatures

Is it possible to define an object interface and then extend the interface, refining method signatures? 是否可以定义一个对象接口,然后扩展该接口,优化方法签名?

I'd like this to to work with strictFunctionTypes set to true . 我希望将它与strictFunctionTypes设置为true

A simple example: 一个简单的例子:

interface Plugin {
    addListener: (eventName: string) => void;
}

interface FooPlugin extends Plugin {
    addListener: (eventName: 'fooChanged') => void;
}

Here I get the following error: 在这里,我得到以下错误:

Interface 'FooPlugin' incorrectly extends interface 'Plugin'.
    Types of property 'addListener' are incompatible.
        Type '(eventName: "fooChanged") => void' is not assignable to type '(eventName: string) => void'.
            Types of parameters 'eventName' and 'eventName' are incompatible.
                Type 'string' is not assignable to type '"fooChanged"'.

Here's a more complex example showing what'd I'd eventually like to be able to do: 这是一个更复杂的示例,显示了我最终想要做的事情:

export interface Plugin {
    addListener: (eventName: string, fn: Function) => void;
}

export interface FooPlugin extends Plugin {
    addListener: (eventName: 'fooInit', fn: (n: { i: boolean }) => void) => void;
    addListener: (eventName: 'fooDestroy', fn: (n: { d: number }) => void) => void;
}

I don't like this solution very much but I suppose that you need this for typing a not-typed library so you can do something like this: 我不太喜欢这种解决方案,但是我想您需要使用它来键入非类型的库,以便您可以执行以下操作:

1) Add generics in Plugin interface 1)在插件界面中添加泛型

export interface Plugin<T, P> {
   addListener: (eventName: T, fn: (value: P) => void) => void;
}

2) Then create a Type with all your listener typed correctly 2)然后创建一个类型,所有您的侦听器正确键入

export type FooPlugin = Plugin<'fooInit', { i: boolean }> & Plugin<'fooDestroy', { d: number 
}>

3) Finally use it in your code 3)最后在您的代码中使用它

let plugin: FooPlugin = require("someLib");
plugin.addListener('fooInit', ({i}) => ...); 
plugin.addListener('fooDestroy', ({d}) => ...); 

For better or for worse, this will work if you declare methods (which are exempt from strictFunctionTypes ) instead of function-valued properties: strictFunctionTypes是好是坏,如果声明方法(而不是strictFunctionTypes )而不是函数值的属性,则这将起作用:

interface Plugin {
    addListener(eventName: string): void;
}

interface FooPlugin extends Plugin {
    addListener(eventName: 'fooChanged'): void;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM