我发现下面的getter函数非常有用和可重用,因为它可以获得属性key
of 的值,任何具有此类属性的对象。
export function keyOf<a>(value: { key: a; }) : a {
return value.key;
}
类似地,我可以定义一个通用的setter函数:
export function withKey<a>(value: { key: a; }, key: a) : void {
value.key = key;
}
唯一的问题是,我不需要返回void
,而是用修改后的key
属性返回原始对象key
。就像这样:
export function withKey<b, a extends { key: b }>(value: a, key: b) : a {
value.key = key;
return value;
}
但是这不是一个有效的TypeScript代码。
问:否则,我如何才能获得返回原始对象及其属性集的类型- the通用setter函数?
更新:
在当前的TypeScript中,类型参数之间的依赖关系是禁止的。我相信这样做是为了使类型系统更简单、更快。然而,这一限制阻止了某些有用的场景,如所讨论的场景。有一种黑客可以将类型参数之间的依赖关系转换为函数依赖关系:
export function withKey<a, b>(
value: a,
key: b,
toAssignable: (value: a) => { key: b } = function<c>(anything: c) : c {
return anything;
}
) : a {
toAssignable(value).key = key;
return value;
}
这看起来像地狱一样丑陋,改变了原来的签名,但它编译和工作。
,有人知道更好的方法吗?
发布于 2015-01-26 11:24:19
我玩了一会儿,我只能想出这个:
// === unsave approach ===
/**
* Test class
*/
class MyClassWithoutKey {
public youCanCallThis() { }
}
/**
* The setter function
*/
function withKeyUnsafe<T>(value: T, key: any) {
(<any>value).key = key;
return value;
}
// compile test
var w = withKeyUnsafe(new MyClassWithoutKey(), 2).youCanCallThis();
这是:
// === typesave approach ===
/**
* Test class
*/
class MyClassWithKey {
key: string;
public youCanCallThis() { }
}
/**
* Helper interface
*/
interface WithKey<T> {
key: T;
}
/**
* Factory function that adds type constraint
*/
function withKeyTypeSave<T>() {
/**
* The actual setter function
*/
return function <WithKeyT extends WithKey<T>>(value: WithKeyT, key: T) {
value.key = key;
return value;
}
}
// compile test -- works
withKeyTypeSave<string>()(new MyClassWithKey(), "new key").youCanCallThis();
// compile test -- fails
withKeyTypeSave<number>()(new MyClassWithKey(), "new key").youCanCallThis();
// compile test -- fails
withKeyTypeSave<string>()(new MyClassWithKey(), 3).youCanCallThis();
https://stackoverflow.com/questions/28011439
复制