![](/img/trans.png)
[英]Typescript mind the order of instantiation in an Object literal?
[英]Limit properties on instantiation of Typescript object
我從這篇文章中知道,可以將類型良好的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
我的變量。 我希望它拋出一個錯誤或不分配它。
我以為不可能,但是我在功能請求中找到了這個有趣的帖子 ,要求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; }'.
不是最直觀的消息,但它可以完成任務。
該解決方案歸功於 GitHub上的RafałŁużyński(mindbrave) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.