基本上,我想要这样的东西:
export type ReturnValueMapper<Func extends (...args: Args[] /* impossible */ ) => any, ReturnValue> = (...args: Args[]) => ReturnValue;
Run Code Online (Sandbox Code Playgroud)
我几乎可以肯定这是不可能的,但我还没有找到确切的确认.
用例是使用stateHandlers改进重构的类型,从而可以定义状态更新器,如下所示:
interface StateUpdaters {
update(field: string): void; // I don't want to specify Partial<State> here
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试只让我的后代暴露一些祖先的属性。我试图通过实现Pick
export class Base {
public a;
public b;
public c;
}
export class PartialDescendant extends Pick<Base, 'a' |'b'> {
public y;
}
Run Code Online (Sandbox Code Playgroud)
但我收到两个错误-
错误:TS2693:“ Pick”仅引用一种类型,但在此处被用作值。
和
错误:TS4020:导出类“ PartialDescendant”的“ extends”子句具有或正在使用私有名称“ Pick”。
我做错什么了吗,还有另一种方法只公开基类的选定属性吗?
当装饰器更改其返回类型时,如何让 TypeScript 推断装饰方法的类型?
在下面的基本示例中,我装饰一个方法以返回字符串化对象:
function jsonStringify() {
return function (target, decoratedFnName: string, descriptor: PropertyDescriptor) {
let decoratedFn = descriptor.value;
let newFn = function () {
let object = decoratedFn.apply(target, arguments);
return JSON.stringify(object);
};
descriptor.value = newFn;
return descriptor;
}
}
class Decorated {
@jsonStringify()
method(name: string, description: string) {
return {
name: name,
description: description
}
}
};
let stringifiedObject = new Decorated().method('Test Name', 'Test Description');
console.log(stringifiedObject.includes('Test Name'));
Run Code Online (Sandbox Code Playgroud)
如果我在 tsconfig.json 中转译 TypeScript "noEmitOnError": false,那么代码将完美运行并在控制台中记录 true。然而,tsc 抱怨错误:
error TS2339: Property …Run Code Online (Sandbox Code Playgroud) 用例:我想知道一个函数在打字稿中执行需要多长时间。我想使用装饰器来达到这个目的。我希望装饰器应该返回时间,以便(我可以进一步使用它),而不仅仅是打印它。
例如:
export function createTimestamps(message: string) {
return function (target: any, name: string, descriptor: PropertyDescriptor) {
const method = descriptor.value;
descriptor.value = async function () {
const startTime = new Date(Date.now());
console.log(
`${message} started at: ${startTime.toLocaleString("en-GB")}`
);
await method.apply(this);
const endTime = new Date(Date.now());
console.log(
`${message} completed at: ${endTime.toLocaleString("en-GB")}`
);
console.log(
`${message} took ${
endTime.getTime() - startTime.getTime()
}ms to complete.`
);
};
};
}
Run Code Online (Sandbox Code Playgroud)
如果我使用上面的函数作为装饰器,那么我希望装饰器返回“endTime.getTime() - startTime.getTime()”,以便我可以进一步使用它。
@creaTimestamp
async newfunc():string{
return "typescript";
}
Run Code Online (Sandbox Code Playgroud)
现在,当我调用上面的函数时,await newfunc()。我可以获取执行时间值以及它返回的字符串吗?
另外,我有很多函数,我想避免在每个函数之上添加装饰器,因此在调用它们时,我想确保装饰器运行并返回计时。有人可以指出我这样的图书馆(如果存在)吗?
有人可以分享一些对上述场景的见解吗,我对装饰器很陌生。谢谢!