简体   繁体   中英

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:

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

This does not work:

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

TS Playground

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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