加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 我如何在Typescript中表达?

发布时间:2020-12-16 09:20:23 所属栏目:安全 来源:网络整理
导读:假设我有一个接口A: interface A { foo: number bar: string} 我有一个通用类型选项: type OptionT = { map: () = T} 然后我从A和Option创建一个新的界面B: interface B { foo: Optionnumber bar: Optionstring} 如何使这个操作更通用? IE浏览器.我想要
假设我有一个接口A:

interface A {
  foo: number
  bar: string
}

我有一个通用类型选项:

type Option<T> = {
  map: () => T
}

然后我从A和Option创建一个新的界面B:

interface B {
  foo: Option<number>
  bar: Option<string>
}

如何使这个操作更通用? IE浏览器.我想要的API是

type B = Lift<A>

Where Lift自动将A的每个成员映射到选项.请注意,A可以有任何数量的任何类型的成员.

电梯如何实施?如果这在TypeScript中是不可能的,有没有人有Scala / Haskell解决方案?

解决方法

好消息:使用TypeScript 2.1.0,现在可以通过 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 } }

相反也是可以的:

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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读