[英]Creating `toFunc` generic method in Typescript?
我在 Ts 中有一個模型,我需要用一些屬性填充它。
當前的代碼簡化是:
var claimSummaryDetails : {
Name : this._store.selectSync("currentUser")
.Result
.Family
.find(m => m.MemberID == openClaim.Member_ID)
}
好的。 這就是事情變得復雜的地方。
請注意,我還沒有填充name
(帶有字符串):
我有一個帶有許多“名稱”選項的對象( englishFirstName
/ localfirstName
)
好的 - 那么我應該顯示哪個名字?
嗯,這就是為什么我們有一個名為isEnglish:boolean
的lang
指標
所以基本上:
如果isEnglish ==true
,我們應該采取:
{Name: this._store.selectSync("currentUser")
.Result
.Family
.find(m => m.MemberID == openClaim.Member_ID).englishfirstname}
除此以外
{Name: this._store.selectSync("currentUser")
.Result
.Family
.find(m => m.MemberID == openClaim.Member_ID).localFirstName}
當然,我可以這樣做:
{Name: isEnglish ? this._store...........englishFirstName : this._store....localFirstName}
但請注意,它會掃描商店兩次,而且時間太長。
好的。
在 C# 中(很久以前)我創建了一個擴展方法,它允許我接受參數並做任何我想做的事情,無論是什么類型:
public static class A
{
public static Tout ToFunc<T, Tout>(this T obj, Func<T, Tout> f)
{
return f(obj);
}
}
class Person
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
void Main()
{
bool isEnglish = true;
Person[] a = new Person[] { new Person() { Prop1 = 1,Prop2=100 }, new Person() { Prop1 = 2,Prop2=200 }, new Person() { Prop1 = 3,Prop2=300 } };
Console.WriteLine(a.First().ToFunc(whatever => isEnglish ?whatever.Prop1 : whatever.Prop2 ));
}
結果:1
請注意這一點:
.ToFunc(whatever => isEnglish ?whatever.Prop1 : whatever.Prop2
whatever
X.toFunc
中 X 的值是X.toFunc
,我都可以訪問它的 props 。
這讓我可以掃描兩次商店,並創建額外的變量/方法
題
我試圖用 TS 做到這一點,但沒有成功:
interface Object {
toFunc(a:(a)=>any): any;
}
Object.prototype.toFunc = function (f:(a)=>any){
f();
}
var g= [{a:1,b:2}]
let res= g.find(d => d.a == 1).toFunc((a) => { if (a.a == 1) return 1; else return 2 })
如何修復我的代碼以支持每種類型的.toFunc(a=>a...)
泛型?
換句話說,我怎樣才能做到這一點:
var claimSummaryDetails : {
Name : this._store.selectSync("currentUser")
.Result
.Family
.find(m => m.MemberID == openClaim.Member_ID)
.toFunc(item=>isEnglish ? item.englishFirstName : item.localFirstName)
}
順便提一句
我想到的一種解決方案是(使用 IIFE):
{Name: ((customer) => this.isEng
? customer.englishfirstname
: customer.localfirstname)(
this._store.selectSync("currentUser")
.Result
.Family
.find(m => m.MemberID == openClaim.Member_ID)) },
但我想知道是否可以創建一個類型化的toFunc
方法。
雖然應該仔細考慮在Object
上添加方法,但如果對this
參數使用泛型參數,則可以獲得要推斷的類型
interface Object {
toFunc<T, R>(this: T, fn:(a: T)=> R): R;
}
Object.prototype.toFunc = function <T, R> (this:T, f:(a:T)=> R){
return f(this);
}
var g= [{a:1,b:2}]
var result = g.find(d => d.a == 1).toFunc(i => this.isEng ? i.a : i.b)
為什么不簡單地在打字稿中使用 getter 和條件語句。 一個簡單的例子:
class Family {
isEnglish = false;
firstName = "FirstName"
lastName = "LastName"
constructor(isEnglish: boolean) {
this.isEnglish = isEnglish;
}
get getName(): string{
if (this.isEnglish) {
return this.firstName
} else {
return this.lastName
}
}
}
let family = new Family(true);
alert(family.getName)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.