小编PRA*_*SER的帖子

在打字稿中按字符串返回不同的类型

鉴于我们有如下两种不同的类型,我们如何根据字符串参数而不提供泛型类型来更改函数的返回值?

interface Type1 { typeName: string; };
interface Type2 { typeVersion: string; };
type AllTypes = Type1 | Type2;

function returnTypes(t: string): AllTypes {
  ...
}

const typeResult = returnTypes('type1');
console.log(typeResult.typeName);
Run Code Online (Sandbox Code Playgroud)

这里没有定义回报!

typescript typescript-generics

5
推荐指数
1
解决办法
5280
查看次数

具有泛型类型的打字稿包装函数

如何在不更改 Typescript 中的泛型类型的情况下包装函数?

function x() {
  console.log('Original Function');
}

function wrapper<T extends Function>(func: T): T {
  // Typescript compiler error:
  // Type '() => void' is not assignable to type 'T'.
  return () => {
    console.log('Wrapped Function');
    func.call(null);
  }
}

const xWrapped = wrapper(x);
xWrapped(); // logged 'Wrapped Function' & 'Original Function'
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics

3
推荐指数
2
解决办法
3932
查看次数

标签 统计

typescript ×2

typescript-generics ×2