我通過總結文章的內容再次寫了它。
我想知道如何根據物件屬性值應用介面。
我在下面寫了一個簡單的示例代碼。
一共有三個節點:root、dept、user。
指定每個節點對應的型別。因此,我們希望根據物件型別屬性來指定介面。
但是,您可以看到您正在手動確認型別,因為您還沒有找到解決方案。
為了解決這個問題,我認為應該用索引型別而不是條件型別來解決。
原因是條件型別是期望根據泛型型別引數計算回傳的,但是當前的問題應該是根據現有型別計算而不是接收型別引數。
但是,即使使用兩種方法也無法解決問題。任何幫助將不勝感激???♂?
export enum NodeType {
root = "root",
dept = "dept",
user = "user",
}
interface Node {
readonly type: NodeType;
title: string;
}
interface RootNode extends Node {
type: NodeType.root;
}
interface DeptNode extends Node {
type: NodeType.dept;
departmentCode: string;
}
interface UserNode extends Node {
type: NodeType.user;
employeeNumber: string;
}
const nodeData: Node[] = [
{
type: NodeType.root,
title: "Company 1",
} as RootNode,
{
type: NodeType.dept,
title: "Department 1",
departmentCode: "557",
// The type is not inferred according to the object property type, so the type must be explicitly asserted.
} as DeptNode,
{
type: NodeType.user,
title: "User 1",
employeeNumber: "201911",
} as UserNode,
];
// I want to be the type of DeptNode interface because the type of object property is NodeType.dept.
const selectDept = nodeData.filter((x) => x.type === NodeType.dept);
selectDept.forEach((x) => {
console.log({
type: x.type,
title: x.title,
// The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
departmentCode: (x as DeptNode).departmentCode,
});
});
uj5u.com熱心網友回復:
我知道如何使用types 而不是interfaces來做到這一點。
您的嘗試有兩個問題:
- 通過使用型別,您可以利用可區分的聯合
(注意
Node型別是三種可能情況的聯合)。 - 對于陣列方法,例如
filterandforEach,推斷演算法不夠聰明,無法理解請求的型別是什么,因此您必須使用簡單的for和 aif。在此處閱讀更多資訊:https : //stackoverflow.com/a/62033938/632445
開始了:
export enum NodeType {
root = "root",
dept = "dept",
user = "user",
}
type NodeBase = {
readonly type: NodeType;
title: string;
}
type RootNode = NodeBase & {
type: NodeType.root;
}
type DeptNode = NodeBase & {
type: NodeType.dept;
departmentCode: string;
}
type UserNode = NodeBase & {
type: NodeType.user;
employeeNumber: string;
}
type Node = RootNode | DeptNode | UserNode;
const nodeData: Node[] = [
{
type: NodeType.root,
title: "Company 1",
},
{
type: NodeType.dept,
title: "Department 1",
departmentCode: "557",
// The type is not inferred according to the object property type, so the type must be explicitly asserted.
},
{
type: NodeType.user,
title: "User 1",
employeeNumber: "201911",
},
];
// I want to be the type of DeptNode interface because the type of object property is NodeType.dept.
for (const x of nodeData) {
if (x.type === NodeType.dept) {
console.log({
type: x.type,
title: x.title,
// The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
departmentCode: (x as DeptNode).departmentCode,
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407293.html
標籤:
