类型变量的Typescript空对象 [英] Typescript empty object for a typed variable

查看:36
本文介绍了类型变量的Typescript空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

  type用户= {...} 

我想创建一个新的 user ,但将其设置为空对象:

  const用户:User = {};//这无法说明属性XX丢失const user:User = {}任意值;//这可行,但我不想使用任何 

我该怎么做?我不希望变量为 null .

解决方案

注意事项

这里有两个值得注意的警告.

您希望用户的类型为 User |.{} Partial< User> ,或者您需要重新定义 User 类型以允许使用空对象.现在,编译器正确地告诉您该用户不是用户.– jcalz

我认为这不应该被认为是正确的答案,因为它创建了一个不一致的类型实例,从而破坏了TypeScript的整个目的.在此示例中,属性 Username 处于未定义状态,而类型注释则表示它不能处于未定义状态.– 刘恩·罗德里格斯(Ian Liu Rodrigues)

答案

TypeScript的

Say I have:

type User = {
...
}

I want to create a new user but set it to be an empty object:

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 the variable to be null.

解决方案

Caveats

Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User 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

Answer

One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "foo@bar.com";

Here is a working example for you.

这篇关于类型变量的Typescript空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆