Skip to content

函数类型表达式

typescript
function greeter(fn: (a: string) => void) {
  fn("Hello, World");
}

通过type命名函数类型

typescript
type GreetFunction = (a:string)=>void;
function greeter(fn:GreetFunction){
  fn("Hello, World!");
}

函数属性声明

typescript
type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}
 
function myFunc(someArg: number) {
  return someArg > 3;
}
myFunc.description = "default description";
 
doSomething(myFunc);

定义构造函数

typescript
type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

使用泛型

typescript
function firstElement<Type>(arr:Type[]):Type|undefined{
  return arr[0];
}
typescript
const map = function <T, U>(arr: T[], func: (arg: T) => U): U[] {
  return arr.map(func);
};
typescript
function longest<Type extends { length: number }>(a: Type, b: Type) {
  if (a.length >= b.length) {
    return a;
  } else {
    return b;
  }
}
 
// longerArray is of type 'number[]'
const longerArray = longest([1, 2], [1, 2, 3]);
// longerString is of type 'alice' | 'bob'
const longerString = longest("alice", "bob");
// Error! Numbers don't have a 'length' property
const notOK = longest(10, 100);
typescript
function combine<Type>(arr1: Type[], arr2: Type[]): Type[] {
  return arr1.concat(arr2);
}
const arr = combine<string|number>(['1','2','3'],['hello'])

可选参数

typescript
function f(x?: number) {
  // ...
}
f(); // OK
f(10); // OK
f(undefined);// OK