最新版本的打字稿是否可以根據通過引數提供的值來縮小物件的屬性,而無需將它們指定為函式的單獨泛型型別?
我希望以下作業,其中函式簽名bar
回傳一個物件,其中鍵作為引數提供。從理論上講,如果引數是恒定的,則應該可以推斷出簽名。
interface ModelType {
id: string;
name: string;
timestamp: Date;
}
class Foo<T, K extends keyof T = keyof T>{
public bar(selectedField : K[]) : Pick<T,K>{
return {} as any;
}
}
const foobar = new Foo<ModelType>().bar(['id','name']);
console.log(foobar.id) //Success
console.log(foobar.name) //Success
console.log(foobar.timestamp) //Should be an error
我嘗試了任何與typeof selectedValues
unarray 的組合,但最終得到了全套 K。
uj5u.com熱心網友回復:
類方法泛型型別
您可以將泛型型別添加到類方法extends
的generic type
類中,如下所示:
class Foo<T, K extends keyof T = keyof T>{
// using generic types in your class method
public bar<L extends K>(selectedField : L[]) : Pick<T,L>{
return {} as any;
}
}
打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470400.html