是否可以在TypeScript中实现函数接口?

Yuh*_*ang 8 typescript

我希望能够做到这一点

class MyFunc extends ((s: string) => boolean) { ... }
Run Code Online (Sandbox Code Playgroud)

这样一个实例MyFunc可以用作一个函数,它接受一个字符串作为输入并返回一个布尔值,如下所示:

const f = new MyFunc();
const b: boolean = f('someString');
Run Code Online (Sandbox Code Playgroud)

这在TypeScript中是否可行?

在Scala等语言中,可以扩展类型String => Boolean,并提供apply实现此目的的方法.

class MyFunc extends (String => Boolean)
val f = new MyFunc()
val b: Boolean = f("someString")
Run Code Online (Sandbox Code Playgroud)

y2b*_*2bd 12

applyTypeScript 中没有默认概念,但是有一些方法可以创建也是函数的类型化对象。

interface MyCallable {
    (param1: string, param2: number): string;

    prop1: string;
    prop2: number;
    extraMethod: (param1: boolean) => boolean;
}

function makeMyCallable(prop1: string, prop2: number): MyCallable {
    let that = ((param1: string, param2: number) => param1 + param2) as MyCallable;

    that.prop1 = prop1;
    that.prop2 = prop2;
    that.extraMethod = (param1: boolean) => !param1;

    return that;
}

let mc = makeMyCallable("3", 4);

mc("3", 4);
mc.prop1 = "string";
mc.prop2 = 5;
mc.extraMethod(false);
Run Code Online (Sandbox Code Playgroud)


Dav*_*ret 12

也许你在考虑这样的事情?

interface FunctionInterface {
    (s: string): boolean;
}

const f: FunctionInterface = s => true;
const b: boolean = f('someString');
Run Code Online (Sandbox Code Playgroud)

  • 对于非箭头函数来说这可能吗?像 `function myFunc(s) Implements FunctionInterface { return true; 之类的东西 }` (4认同)
  • 这是函数类型的详细文档:https://www.typescriptlang.org/docs/handbook/interfaces.html (2认同)

CBa*_*arr 0

如果您想要的只是一个接受字符串并返回布尔值的简单函数,则不需要为此使用类。

const myFunc = (s: string): boolean => {
  return s !== "";  //whatever logic is needed here
};
Run Code Online (Sandbox Code Playgroud)

但是,是的,你可以在 TypeScript 中扩展类

class MyBaseClass {
  constructor() { }

  public doThing = (s: string): boolean => {
    return s !== "";  //whatever logic is needed here
  }
}

class MyFunc extends MyBaseClass {
  constructor() {
    super();
  }
}

const f = new MyFunc();
const b = f.doThing("hi"); //returns a boolean
Run Code Online (Sandbox Code Playgroud)

已更新以回复评论

正如下面另一个答案中提到的,您不能真正new创建一个类,将该实例分配给一个变量,然后将其作为函数调用。不过,您可以在创作中这样做,如下所示:

class MyBaseClass {
  constructor() { }

  public doThing = (s: string): boolean => {
    return s !== "";  //whatever logic is needed here
  }
}

class MyFunc extends MyBaseClass {
  constructor(private s: string) {
    super();
    this.doThing(this.s);
  }
}

const f = new MyFunc("hi"); //returns a boolean
Run Code Online (Sandbox Code Playgroud)

您可以在此处的 Typescript Playground 上使用上面的代码