代码之家  ›  专栏  ›  技术社区  ›  Corno

在typescript中用类型参数实现函数时,是否可以引用类型

  •  0
  • Corno  · 技术社区  · 4 年前

    我想在typescript中拆分类型规范和函数的实现

    例如:

    如果我有这样的类型

    type MyFuncType = () => void
    

    我可以创建这样一个类型的实例的实现:

    const myFuncImp: MyFuncType = () => {
        //implementation
    }
    

    我现在想用类型参数来做这件事。我的方法不起作用:

    type MyFuncType<T> = () => void
    
    const myFuncImp: MyFuncType = () => {
        //implementation
    }
    

    这将导致一个错误:

    Generic type 'MyFuncType' requires 1 type argument(s)
    

    有别的办法吗?

    0 回复  |  直到 4 年前
        1
  •  0
  •   Corno    4 年前

    将泛型参数附加到函数类型,而不是类型别名:

    type MyFuncType = <T>(a: string) => void;
    // instead of: type MyFuncType<T> = () => void;
    
    const myFuncImp: MyFuncType = <T>(a) => {
        //implementation
        const myArray: T[] = [];
        a.endsWith("foo")
    };