与this question类似,但我希望类上的é™æ€æˆå‘˜ä¹Ÿå¯ç”¨ã€‚
这就是我æ£åœ¨å°è¯•çš„:
function noNew<T>(clazz: new () => T): { (): T }
function noNew<T, T1>(clazz: new (arg1: T1) => T): { (arg1: T1): T }
function noNew<T>(clazz: new (...a: any[]) => T): { (...b: any[]): T } {
const factory = (...args: any[]) => {
return new clazz(...args);
};
// I want the return type annotation to be aware of this step
Object.assign(factory, clazz);
return factory;
}
class Test {
static one() {}
two: 'two';
}
const test = noNew(Test);
test.one(); // <- unresolved function or method 'one'
æ£å¦‚您所看到的,打å—稿并ä¸çŸ¥é“我在返回值ä¸æ·»åŠ 了é™æ€æˆå‘˜ã€‚我如何将其表示为注释?
如果您å¯ä»¥æŽ’除test.prototype
,则å¯ä»¥èŽ·å¾—奖励积分。
ç”案 0 :(得分:2)
è¿™æ ·çš„äº‹æƒ…æ€Žä¹ˆæ ·ï¼š
// works for some constructor types
type ConstructorToFunction<C extends new (...args: any[]) => any> = (
C extends (new () => infer T) ? () => T :
C extends (new (a: infer A) => infer T) ? (a: A) => T :
C extends (new (a: infer A, b: infer B) => infer T) ? (a: A, b: B) => T :
C extends (new (...args: any[]) => infer T) ? (...args: any[]) => T :
C // bail out
) & { [K in Exclude<keyof C, 'prototype'>]: C[K] }
我在这里使用TypeScript 2.8ä¸å¼•å…¥çš„conditional typesæ¥å°è¯•å°†æž„é€ å‡½æ•°è½¬æ¢ä¸ºå…·æœ‰ç›¸åŒå‚数的函数。大æ¡ä»¶éƒ¨åˆ†å–代了您的é‡è½½é›†ï¼Œä¸Ž{[K in Exclude...
的交集负责å¤åˆ¶é™æ€éƒ¨åˆ†ã€‚
以下是我输入noNew()
功能的方法:
function noNew<C extends new (...args: any[]) => any>(
clazz: C
): ConstructorToFunction<C>;
function noNew(
clazz: new (...args: any[]) => any
): { (...args: any[]): any } {
const factory = (...args: any[]) => {
return new clazz(...args);
};
Object.assign(factory, clazz);
return factory;
}
å•ä¸ªé‡è½½ä»ç„¶æœ‰ç”¨ï¼Œå› 为返回æ¡ä»¶ç±»åž‹çš„函数很难在没有大é‡ç±»åž‹æ–è¨€çš„æƒ…å†µä¸‹å®žçŽ°ï¼Œå› æ¤é‡è½½ä½¿æˆ‘从ä¸è§£è„±å‡ºæ¥ã€‚
让我们看看它是å¦æœ‰æ•ˆï¼š
class Test {
static one() { }
two: 'two' = 'two';
}
const test = noNew(Test);
test.one(); // works
看起æ¥ä¸é”™ã€‚希望有所帮助ï¼