- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
假设我有:
type User = {
...
}
我想创建一个新的 user
但将其设置为一个空对象:
const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use any
我该怎么做?我不希望变量为 null
。
最佳答案
这里有两条来自评论的有值(value)的警告。
Either you want user to be of type
User | {}
orPartial<User>
, or you need to redefine theUser
type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalz
I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Username
is left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
design goals of TypeScript 之一是“在正确性和生产力之间取得平衡。”如果这样做对您来说是富有成效的,请使用 Type Assertions为类型变量创建空对象。
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "foo@bar.com";
关于类型化变量的 TypeScript 空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339065/
我在 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
我是一名优秀的程序员,十分优秀!