Typescript 泛型函数类型
我可以创建如下函数类型:Typescript 泛型函数类型,typescript,Typescript,我可以创建如下函数类型: type read = (name: string) => void; const test:read = (value: string) => { console.log(value); } type read<T> = (name:T) => void; 如果我将改为这样,那么测试的实现会是什么样子: type read = (name: string) => void; const test:read = (valu
type read = (name: string) => void;
const test:read = (value: string) => {
console.log(value);
}
type read<T> = (name:T) => void;
如果我将改为这样,那么测试的实现会是什么样子:
type read = (name: string) => void;
const test:read = (value: string) => {
console.log(value);
}
type read<T> = (name:T) => void;
type read=(名称:T)=>void;
这不起作用:
const test<T>:read<T> = (value: T) => {
console.log(value);
}
const测试:read=(值:T)=>{
console.log(值);
}
新答案
通用命名函数使用以下语法:
function test<T>(name: T) : void {
console.log(name);
}
功能测试(名称:T):无效{
console.log(名称);
}
以及将函数赋给常数的语法:
const test = <T>(name: T) : void => {};
const test=(名称:T):void=>{};
旧答案
这就是你想要的:
type read<T> = (name:T) => void;
const test : read<string> = (name) => {
console.log(name);
}
type read=(名称:T)=>void;
常量测试:读取=(名称)=>{
console.log(名称);
}
然后,要扩展,如果希望一个函数采用多种类型:
const testFlex : read<string|number> = (name) => {
console.log(name);
}
testFlex('a');
testFlex(1);
const testFlex:read=(name)=>{
console.log(名称);
}
testFlex(“a”);
testFlex(1);
以及针对不同类型的不同功能:
const testString : read<string> = (name) => {
console.log(name);
}
const testNumber : read<number> = (name) => {
console.log(name);
}
testString('a');
testNumber(1);
const testString:read=(name)=>{
console.log(名称);
}
const testNumber:read=(name)=>{
console.log(名称);
}
testString('a');
测试编号(1);
新答案
通用命名函数使用以下语法:
function test<T>(name: T) : void {
console.log(name);
}
功能测试(名称:T):无效{
console.log(名称);
}
以及将函数赋给常数的语法:
const test = <T>(name: T) : void => {};
const test=(名称:T):void=>{};
旧答案
这就是你想要的:
type read<T> = (name:T) => void;
const test : read<string> = (name) => {
console.log(name);
}
type read=(名称:T)=>void;
常量测试:读取=(名称)=>{
console.log(名称);
}
然后,要扩展,如果希望一个函数采用多种类型:
const testFlex : read<string|number> = (name) => {
console.log(name);
}
testFlex('a');
testFlex(1);
const testFlex:read=(name)=>{
console.log(名称);
}
testFlex(“a”);
testFlex(1);
以及针对不同类型的不同功能:
const testString : read<string> = (name) => {
console.log(name);
}
const testNumber : read<number> = (name) => {
console.log(name);
}
testString('a');
testNumber(1);
const testString:read=(name)=>{
console.log(名称);
}
const testNumber:read=(name)=>{
console.log(名称);
}
testString('a');
测试编号(1);
否,我想创建一个与read
@AlexanderZeitler签名匹配的命名通用函数我已更新答案以匹配您的反馈否,我想创建一个与read
@AlexanderZeitler签名匹配的命名通用函数我已更新答案以匹配您的反馈