简体   繁体   English

通用函数类型

[英]Generic function type

I can create a function type like this:我可以创建这样的函数类型:

type read = (name: string) => void;

const test:read = (value: string) => {
  console.log(value);
}

How would the implementation of test look like, if I would change read like this: test的实现会是什么样子,如果我像这样改变read

type read<T> = (name:T) => void;

This does not work:这不起作用:

const test<T>:read<T> = (value: T) => {
  console.log(value);
}

TS Playground TS游乐场

New Answer新答案

Generic named functions use the following syntax:通用命名函数使用以下语法:

function test<T>(name: T) : void {
    console.log(name);
}

And the syntax for assigning the function to a constant:以及将函数分配给常量的语法:

const test = <T>(name: T) : void => {};

Typescript Playground Example 打字稿游乐场示例

More reading on generics 更多关于泛型的阅读

Old Answer旧答案

This is what you want:这就是你想要的:

type read<T> = (name:T) => void;

const test : read<string> = (name) => {
      console.log(name);
}

Then to extend, if you want one function to take multiple types:然后扩展,如果您希望一个函数采用多种类型:

const testFlex : read<string|number> = (name) => {
    console.log(name);
}

testFlex('a');
testFlex(1);

And separate functions for separate types:以及不同类型的单独功能:

const testString : read<string> = (name) => {
    console.log(name);
}

const testNumber : read<number> = (name) => {
    console.log(name);
}

testString('a');
testNumber(1);

Typescript Playground Example 打字稿游乐场示例

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

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