Javascript 类型变量的打字稿空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45339065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript empty object for a typed variable
提问by Kousha
Say I have:
说我有:
type User = {
...
}
I want to create a new userbut set it to be an empty object:
我想创建一个新的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
How do I do this? I don't want to the variable to null.
我该怎么做呢?我不想将变量设置为null.
回答by Shaun Luttin
Caveats
注意事项
Here are two worthy caveats from the comments.
以下是评论中的两个有价值的警告。
Either you want user to be of type
User | {}orPartial<User>, or you need to redefine theUsertype to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalzI 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
Usernameis left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
您希望 user 的类型为
User | {}或Partial<User>,或者您需要重新定义User类型以允许空对象。现在,编译器正确地告诉您用户不是用户。——jcalz我认为这不应该被视为一个正确的答案,因为它创建了一个不一致的类型实例,破坏了 TypeScript 的整个目的。在此示例中,属性
Username未定义,而类型注释表示它不能未定义。——Ian Liu Rodrigues
Answer
回答
One of the design goals of TypeScriptis to "strike a balance between correctness and productivity."If it will be productive for you to do this, use Type Assertionsto create empty objects for typed variables.
TypeScript的设计目标之一是“在正确性和生产力之间取得平衡”。如果这样做对您有帮助,请使用类型断言为类型变量创建空对象。
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "[email protected]";
Here is a working example for you.
这是一个工作示例。
回答by pixelpax
Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.
真的取决于你想要做什么。类型是打字稿中的文档,因此您想表明在创建类型时应该如何使用这个东西的意图。
Option 1: If Users might have some but not all of the attributes during their lifetime
选项 1:如果用户在其生命周期中可能拥有部分而非全部属性
Make all attributes optional
使所有属性可选
type User = {
attr0?: number
attr1?: string
}
Option 2: If variables containing Users may begin null
选项 2:如果包含用户的变量可能以 null 开头
type User = {
...
}
let u1: User = null;
Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:Userwithout any assignment.
虽然,实际上,如果重点是在知道将分配给它的内容之前声明 User 对象,您可能希望不let u1:User进行任何分配。
Option 3: What you probably want
选项 3:您可能想要的
Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.
确实,打字稿的前提是确保您符合您在类型中勾勒出的心智模型,以避免犯错误。如果你想一个一个地向一个对象添加东西,这是 TypeScript 试图让你不要这样做的习惯。
More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.
更有可能的是,您想要创建一些局部变量,然后当它准备好成为一个完整的用户时分配给包含用户的变量。这样你就永远不会留下一个部分形成的用户。那些东西太恶心了。
let attr1: number = ...
let attr2: string = ...
let user1: User = {
attr1: attr1,
attr2: attr2
}
回答by Nazehs
you can do this as below in typescript
您可以在打字稿中按如下方式执行此操作
const _params = {} as any;
_params.name ='nazeh abel'
since typescript does not behave like javascript so we have to make the type as any otherwise it won't allow you to assign property dynamically to an object
由于打字稿的行为不像 javascript,所以我们必须将类型设为任何类型,否则它将不允许您将属性动态分配给对象
回答by CatalinBerta
If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:
如果您声明一个空对象字面量,然后稍后分配值,那么您可以将这些值视为可选的(可能存在也可能不存在),因此只需将它们键入为带有问号的可选:
type User = {
Username?: string;
Email?: string;
}


