- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我的示例用例。
type someEnum = 'a' | 'b';
const someObj: { [K in someEnum]: string } = {
a: 'a',
b: 'b',
};
const a: Array<someEnum> = ['a', 'b'];
// In Future update someEnum
type someEnum = 'a' | 'b' | 'c';
// Gives an error;
// Property 'c' is missing in type '{ a: string; b: string; }'
// but required in type '{ a: string; b: string; c: string; }'.
const someObj: { [K in someEnum]: string } = {
a: 'a',
b: 'b',
};
// No error;
const a: Array<someEnum> = ['a', 'b'];
// Is There someThing like;
// const typedArray: [K in someEnum]
如果有这样的功能,那真是太酷了;是否有一些功能可以实现相同的功能。提前致谢。
最佳答案
很容易使用一些变通方法来获得 tuple to union, please don't use it .
您可以通过多种方式解决此问题,最简单的方法是如果枚举在您的控制之下,则从数组而不是枚举开始:
const allPosibilitieForSomeEnum = ['a', 'b' , 'c'] as const
type someEnum = typeof allPosibilitieForSomeEnum[number];
您可以改用对象并使用 keys
获取 key 。
或者您可以使用验证所有成员都存在的函数:
type someEnum = 'a' | 'b' | "c";
function checkEnum<TEnum>() {
return function <TActual extends TEnum[]>(...p: TActual & ([TEnum] extends [TActual[number]] ? {} : {
error: ["Array does not contain all members, expected: ", TEnum, "found:", TActual[number]]
})) {
return p
}
}
const someObj = checkEnum<someEnum>()("a", "b", "c")
const someObj2 = checkEnum<someEnum>()("a", "b") /// Property 'error' is missing in type '["a", "b"]' but required in type '{ error: ["Array does not contain all members, expected: ", someEnum, "found:", "a" | "b"]; }'.
关于Typescript - 如何获取类型化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57323618/
我在 vscode 中使用带有 TypeScript 的 Svelte,并且在 vscode 中安装了 Svelte 扩展。 在我的 App.svelte 中有 // a bunch of co
我想延长go-validator返回更好的类型: type Error map[string][]error // Will output the first error when stringifi
在 python 中,您可以定义具有自动值的类型化枚举: import enum from enum import auto class Ordinals(enum.IntEnum): FIRST
我有一个 custom set我想在打字 Racket 中使用它。一世 要求它使用 require/typed与 #:opaque custom-set?操作说明。它工作,除了代码在运行时失败,当我
下面2种设置HttpClient的场景有什么区别吗? 我应该更喜欢一个吗? 输入客户端: public class CatalogService { private readonly Http
我正在尝试创建一个 dbTyped 和大小的 SqlParameters 数组。这工作正常,但如果我需要另一列,则会导致更改两个地方的代码。 SqlParameter[] parameters = {
我有一个用例,其中复杂的 UI 层次结构需要在 iframe 中呈现,但处理它的逻辑(创建、输入文档、事件处理、退出文档)需要在主框架/应用程序中。 我在获取对 iframe 的 Document 实
我最近将 VS 2005 升级到了 2010 年,对 LinQ 还很陌生。也许有人可以把我放在正确的方式。 背景 : 我有一个类型化数据集,并且使用 Table AccessRule 扩展了标准 SQ
我问这个只是为了澄清我的想法是否正确。 静态/动态类型如果变量的类型在编译时已知,则语言是静态类型的。这实际上意味着您作为程序员必须指定每个变量的类型。示例:Java、C、C++。 如果在运行时解释变
当我使用 CultureInfo Typed DataMember 调用我的 WCF 服务的方法时,它抛出 CommunicationException。 我该如何解决这个问题? The InnerE
我想将项目转换为字符串数组或用于填充 ListBox.DataSource 的类型。该类型已覆盖 ToString(),但我似乎无法将其转换,甚至无法转换为 String[]。 String[] a
如何获取/打印(键入的)查询后面的 JPQL 查询字符串,即设置之后参数? (例如,用于调试目的) 一个简单的 toString() 似乎并不能解决问题... 谢谢 最佳答案 没有“最终被翻译成最终
这是 Scala 2.8.0 beta 对这个问题的跟进: What is a proper way to manage flexible, typed, immutable data structu
我是一名优秀的程序员,十分优秀!