我如何在Typescript中表达这一点? [英] How do I express this in Typescript?
问题描述
假设我有一个接口 A
:
interface A {
foo:number
bar:string
}
我有一个通用类型 Option
:
type Option< T> = {
map:()=> T
}
然后我创建一个新接口 B
和期权
:
interface B {
foo:Option< number>
bar:选项< string>
}
如何使这个操作更通用? IE浏览器。我想要的API是:
type B = Lift< A>
其中 Lift
会自动映射 A
转换为期权
。注意 A
可以有任意数量的成员,任何类型的成员。
如何实现电梯
?如果在TypeScript中这是不可能的,那么是否有人有Scala / Haskell解决方案?
好消息:使用TypeScript 2.1.0 ,现在可以通过映射类型:
键入选项< T> = {map()=> T};
类型OptionsHash< T> = {[key in T]中的K:选项< T [K]> };
函数optionsFor< T> ;(结构:T):OptionsHash< T> {...};
let input = {foo:5,bar:'X'};
let output = optionsFor(input);
//输出现在输入为{foo:{map:()=> number},bar:{map:()=>字符串}}
反过来也是可能的:
function retreiveOptions< T>(hash:OptionsHash< T>):T {...};
let optionsHash = {
foo:{map(){return 5; }},
bar:{map(){return'x'; }}
};
let optionsObject = retreiveOptions(optionsHash);
// optionsObject现在输入为{foo:number,bar:string}
Let's say I have an interface A
:
interface A {
foo: number
bar: string
}
And I have a generic type Option
:
type Option<T> = {
map: () => T
}
Then I create a new interface B
from A
and Option
:
interface B {
foo: Option<number>
bar: Option<string>
}
How can I make this operation more general? Ie. The API I want is:
type B = Lift<A>
Where Lift
automatically maps each member of A
to an Option
. Note that A
can have any number of members, of any type.
How can I implement Lift
? If this is not possible in TypeScript, does anyone have a Scala/Haskell solution?
Good news: With TypeScript 2.1.0, this is now possible via Mapped Types:
type Option<T> = { map() => T };
type OptionsHash<T> = { [K in keyof T]: Option<T[K]> };
function optionsFor<T>(structure: T): OptionsHash<T> { ... };
let input = { foo: 5, bar: 'X' };
let output = optionsFor(input);
// output is now typed as { foo: { map: () => number }, bar: { map: () => string } }
The opposite is also possible:
function retreiveOptions<T>(hash: OptionsHash<T>): T { ... };
let optionsHash = {
foo: { map() { return 5; } },
bar: { map() { return 'x'; } }
};
let optionsObject = retreiveOptions(optionsHash);
// optionsObject is now typed as { foo: number, bar: string }
这篇关于我如何在Typescript中表达这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!