鉴于我们有如下两种不同的类型,我们如何根据字符串参数而不提供泛型类型来更改函数的返回值?
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 中的泛型类型的情况下包装函数?
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)