简体   繁体   English

在Typescript中,是否可以从现有对象中声明“类型”?

[英]In Typescript, Is it possible to declare “type” from an existing object?

Say, I have a function like this: 说,我有一个这样的功能:

function plus(a: number, b: number) { return a + b }

Of course, it's type is (a: number, b: number) => number as function in Typescript. 当然,它的类型是(a: number, b: number) => number作为Typescript中的函数。

If I want to use this function as an "argument" for another without really declare its type, I could use the default argument trick: 如果我想将此函数用作另一个函数的“参数”而不真正声明其类型,则可以使用默认的参数技巧:

function wrap(fn = plus) { ... }

If I don't want it to be the default argument, do I have any other choice besides explicitly declare its type ? 如果我不希望它成为默认参数, 除了显式声明其类型之外我是否还有其他选择?

In short, I don't want this function wrap(fn: (a: number, b: number) => number) { ... } , but I do want something like this function wrap(fn: like(plus)) { ... } . 简而言之,我不需要此function wrap(fn: (a: number, b: number) => number) { ... } ,但我确实想要这样的function wrap(fn: like(plus)) { ... }

What about using generics: 那么使用泛型呢?

function plus(a: number, b: number) { return a + b }

function wrap<T extends Function>(fn: T) {
    fn();
}

// Works 
var wrappedPlus = wrap<typeof plus>(plus);

// Error: Argument of type '5' is not assignable to parameter of type '(a: number, b: number) => number'.
var wrappedPlus = wrap<typeof plus>(5);

// Error: Argument of type '5' is not assignable to parameter of type 'Function'.
var wrappedPlus = wrap(5);

function concat(a: string, b: string) { return a + b }

// Error: Argument of type '(a: number, b: number) => number' is not assignable to parameter of type '(a: string, b: string) => string'.
var wrappedPlus = wrap<typeof concat>(plus);

Thanks to @OweR ReLoaDeD, type fn = typeof plus is a valid statement, so this works: 感谢@OweR ReLoaDeD, type fn = typeof plus是有效的语句,因此可以运行:

function plus(a: number, b: number) { return a + b }
function wrap(fn: typeof plus) { }

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

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