Typescript interface函数类型以及重载

interface 函数类型

//interface 函数类型
interface Foo {
    (a: string): string
}

const foo:Foo=(a:string)=>a;//箭头函数定义具体实现
foo("hello");//输出hello

函数重载 范例1

function doSomething(input: string): string
function doSomething(input: string[]): string[]
//以上声明也可以使用 interface :
interface DoSomething{
    (input: string): string
    (input: string[]): string[];    
}
//定义一个函数,兼容以上两个声明的参数和返回值
function doSomething(input: string | string[]): any {
    // implementation details
    if(typeof input === "string") {
        console.log(input);
        return input;
    } else {
        console.log(input.join(','))
        return input;
    }
}

const foo:DoSomething=doSomething;
foo("hello");//调用第一种形式,输出 "hello"
foo(["hello","world"]);//调用第二种形式,输出 "hello,world" 

函数重载 范例2

参数可能是函数

//函数重载,接口形式,参数为空或是一个函数
interface DoSomething{
  (): string;
  (getter: (from: number, to: number) => string): string;
}

//定义兼容两种参数和返回值的函数,参数为无参或者函数(fun?:),返回值为string
function doSomething(fun?:(from: number, to: number)=>string){
    if (typeof fun=== 'function') 
      return fun(2,3);
    else
      return "hello";
  }


const foo: DoSomething= doSomething;

const a=foo();//调用doSomething的无参形式
const b=foo((from,to)=>"hello".substring(from,to));//调用doSomething的函数参数形式

console.log(a);//输出 "hello"
console.log(b);//输出 "l"

测试

https://www.typescriptlang.org/play/

posted @ 2025-06-08 19:59  悠哉大斌  阅读(39)  评论(0)    收藏  举报