我在 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 的值,我可以访问它的属性。
这让我无需扫描两次商店,并创建额外的变量/方法
问题
我尝试用 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)
关于typescript - 在 Typescript 中创建 `toFunc` 泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053152/