Reputation: 13109
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);
}
Upvotes: 0
Views: 55
Reputation: 1040
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 => {};
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);
Upvotes: 2