gpt4 book ai didi

类型化变量的 TypeScript 空对象

转载 作者:IT王子 更新时间:2023-10-29 03:14:14 32 4
gpt4 key购买 nike

假设我有:

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 | {} 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

回答

design goals of TypeScript 之一是“在正确性和生产力之间取得平衡。”如果这样做对您来说是富有成效的,请使用 Type Assertions为类型变量创建空对象。

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

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

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

这里是 a working example for you .

Here are type assertions working with suggestion.

关于类型化变量的 TypeScript 空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339065/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com