![](/img/trans.png)
[英]In TypeScript, how can i get a generic type parameter to be inferred in a method that has multiple type parameters?
[英]How to get type of each parameter for generic method
我正在尋找一種獲取傳遞給構造函數的函數的參數類型信息的方法。
export class Test<T> {
constructor(
test: ((... params : any[]) => T) | (( ... params : any[] ) => Promise<T>
) {
// Convert function or promise to promise
this.test = this.test = (...params: any[]) => Promise.resolve(test(...params))
}
// How I store the promisify'd function/promise
private test : (...params) => Promise<T>
// I want to see typing information on the parameters for this method
public async execute(...params: any[]) : Promise<any> {
try {
return await this.test(...params)
} catch (error) {
return error
}
}
傳入函數或promise時,我將其存儲為promise。 當前,鍵入信息已丟失。
在execute方法中,我希望能夠看到有關要傳入的參數的類型信息; 它們應與原始函數的參數匹配。
例如;
let test = new Test( (a: number, b: string) : string => `${a}${b}`)
let output : string = test.execute(1, 'b') // should compile
let output : number = test.execute(1, 'b') // should not compile
let output : string = test.execute('b', 1) // should not compile, and this is the one I'm looking for.
有任何想法嗎? 我想知道我是否可以巧妙地使用keyof
。
無法在運行時獲取參數類型,類型信息在編譯期間會全部刪除。 但是,您可以在構造函數中添加一個額外的參數,並將其作為布爾文字類型鍵入,這樣,如果函數返回promise,則第二個參數必須為true,如果返回值,則第二個參數必須為false:
export class Test<T> {
constructor(test: ((... params : any[]) => T), isPromise: false)
constructor(test: ( ... params : any[] ) => Promise<T>, isPromise: true)
constructor(
test: ((... params : any[]) => T) | (( ... params : any[] ) => Promise<T>),
isPromise: boolean
) {
// Convert function or promise to promise
if(!isPromise) {
this.test = (...params: any[]) => Promise.resolve(test(...params))
} else {
this.test = test;
}
}
// How I store the promisify'd function/promise
private test : (...params: any[]) => Promise<T>
}
let test = new Test<string>((a: number, b: string) : string => `${a}${b}`, false) //ok
let test2 = new Test<string>( (a: number, b: string) : string => `${a}${b}`, true) // compiler error
let test3 = new Test<string>( (a: number, b: string) => Promise.resolve(`${a}${b}`), true) //ok
let test4 = new Test<string>( (a: number, b: string) => Promise.resolve(`${a}${b}`), false) // compiler error
提出了可變參數的類型,但仍在討論中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.