gpt4 book ai didi

javascript - 限制 Typescript 对象实例化的属性

转载 作者:行者123 更新时间:2023-11-30 06:21:07 26 4
gpt4 key购买 nike

我知道这个article类型良好的 JSON 可以很容易地分配给一个对象。例如类:

export class User {
id?: number;
username: string;

constructor(username: string) {
this.username = username;
}
}

如果我有一个 JSON 格式的变量 jsonUser:

const jsonUser = {
username: bob,
};

然后我可以轻松地说:

user: User = <User>jsonUser;

我的问题是如何编写一个类,如果可能的话,它会限制该类可以具有的属性。例如:

const jsonUser = {
username: bob,
email: bob@bob.bob
};

我上面定义的 User 类中没有电子邮件。目前,它允许将 email 作为属性分配给类型为 User 的变量。我宁愿它抛出错误或不分配它。

最佳答案

我认为这是不可能的,但我发现了this interesting post在 TypeScript 中对精确类型的功能请求中。

基本上你可以这样做:

export class User {
id?: number;
username: string;

constructor(username: string) {
this.username = username;
}
}

type Exact<A extends object> = A & {key: keyof A};

const jsonUser = {
username: 'bob',
};

const jsonUser2 = {
username: 'bob',
id: 2
};

const jsonUser3 = {
username: 'bob',
email: 'bob@bob.bob'
};

const user: User = jsonUser as Exact<User>; // OK
const user2: User = jsonUser2 as Exact<User>; // OK
const user3: User = jsonUser3 as Exact<User>; // TypeScript error

最后的作业给我以下 TypeScript 错误:

Conversion of type '{ username: string; email: string; }' to type 'Exact<User>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type '{ username: string; email: string; }' is not comparable to type '{ key: "id" | "username"; }'.
Property 'key' is missing in type '{ username: string; email: string; }'.

不是最直观的消息,但它完成了工作。

解决方案归功于 Rafał Łużyński (mindbrave)在 GitHub 上。

关于javascript - 限制 Typescript 对象实例化的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53017277/

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