我有一個函式可以生成一個名為節點的物件陣列:
type Node = {
type: 'text' | 'entity';
// A node of type 'entity' for sure has props defined while a 'text' node does not have them.
// I also require those nodes to be in the same array when returned from the buildNodes function
props?: EntitySpecificProps;
}
type EntitySpecificProps = {
id: string;
}
function buildNodes(): Node[] {
...
return nodes;
}
現在假設我生成了一些節點并將它們傳遞給另一個定義為的函式:
function useEntityNode(props: EntitySpecificProps){
...
}
const nodes = buildNodes();
// typescript gives error because node props may be possibly undefined (given the optional type of 'props').
nodes.map((node) => node.type === 'text' ? node : useEntityNode(node.props))
如果節點的 type 欄位是 type ,我如何約束要定義的節點道具entity
?
uj5u.com熱心網友回復:
Optional "?"
當型別為"entity"
使用此NodeUnion
映射轉換時,您可以通過洗掉 from 道具來完成這項作業。
NodeUnion
確保如果type = "text"
我們得到{ type: "text", props ?: T }
如果type = "entity"
我們得到{ type: "entity", props: T }
ie Props 欄位成為必填項
export type Node = {
type: 'text' | 'entity';
props?: EntitySpecificProps;
}
/* This makes sure that if type = 'text' we get { type: 'text', props ?: T }
if type = 'entity' we get { type: 'entity', props: T } ie Props field becomes required
*/
export type NodeUnion =
| Node["type"] extends infer T
? T extends any
? T extends 'entity'
? Required<Node> & { type: T }
: Node & { type: T }
: never
: never
export type EntitySpecificProps = {
id: string;
}
declare function buildNodes(): NodeUnion[]
declare function useEntityNode(props: EntitySpecificProps): void
const nodes = buildNodes();
nodes.map((node) => node.type === 'text' ? node : useEntityNode(node.props))
代碼游樂場
uj5u.com熱心網友回復:
您可以Node
在其單獨的type
. 然后可以通過它們的type
屬性來區分這些型別。
type _Text = {
type: 'text'
}
type Entity = {
type: 'entity'
props: EntitySpecificProps
}
type EntitySpecificProps = {
id: string;
}
type _Nodes = _Text | Entity
function buildNodes(): _Nodes[] {
return [];
}
function useEntityNode(props: EntitySpecificProps){}
const nodes = buildNodes();
nodes.map((node) => node.type === 'text' ? node : useEntityNode(node.props))
注意:我在這里為某些型別添加了前綴,_
因為名稱Text
與Node
現有型別發生沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466997.html
標籤:打字稿