[英]Create type from composed string literal types
我有三個像這樣的 Typescript 類型:
type Mum = {
stage: "here" | "are" | "some" | "stages";
};
type Dad = {
stage: "more" | "steps" | "that" | "could" | "happen";
};
type Child = Mum | Dad;
我有一個 function 消耗Child
:
function myFunc(person: Child): void {
switch (person.stage) {
case "here":
//doThings();
}
}
但我不想傳遞整個Child
類型,只傳遞stage
。 如何更改此 function 簽名,以便它在不使用any
或保留字符串文字的手動副本的情況下接受stage
?
function myFunc(stage: any): void {
switch (stage) {
case "here":
//doThings();
}
}
您可以使用索引訪問類型來獲取Child
中的stage
類型:
function myFunc(stage: Child ['stage']): void {
switch (stage) {
case "here":
//doThings();
}
}
您可以做兩件事,要么直接從Child
類型訪問stage
,要么創建您的Child
類型的Stage
類型
type Mum = {
stage: "here" | "are" | "some" | "stages";
};
type Dad = {
stage: "more" | "steps" | "that" | "could" | "happen";
};
type Child = Mum | Dad;
function myFunc(stage: Child['stage']): void {
switch (stage) {
case "here":
//doThings();
}
}
type Stages = Child['stage']
function myFunc2(stage: Stages): void {
switch (stage) {
case "here":
//doThings();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.