簡體   English   中英

為什么歧視聯合 typescript 不起作用?

[英]Why discriminated union typescript doesn't work?

我有這些類型

type TARGET_EDIT_SKILL = {
  section: 'skills';
  property: 'type';
  index: number;
  foobar: string;
};

type TARGET_EDIT_EXPERIENCE = {
  section: 'experience';
  property: 'time' | 'position' | 'name' | 'summary';
  index: number;
};

type ACTION_EDIT_SECTION = {
  type: typeof EDIT_SECTION;
  payload: {
    target: TARGET_EDIT_SKILL | TARGET_EDIT_EXPERIENCE;
    value: string;
  };
};

export type Actions =
  | ACTION_UPDATE_DATA
  | ACTION_EDIT_TITLE
  | ACTION_EDIT_SKILL
  | ACTION_EDIT_SECTION;

然后在減速機

case actions.EDIT_SECTION: {
      const { target, value } = action.payload;
      const { section, property, index } = target;

      if (section === 'skills') {
        console.log(target.foobar);
        return property === 'time';
      }

      ...
    }

但我收到 typescript 錯誤“'TARGET_EDIT_EDUCATION' 類型上不存在屬性 'foobar'”。 為什么? 我想如果我用部分條件縮小類型,那么 foobar 必須存在。 以及為什么要return property === 'time'; 是不是類型never 帶有“技能”部分的類型永遠不存在time

- 編輯

還有一件事,我有

const newSetion = [...state[target.section]];
// const newSection: (Skill | Education | Experience | Language)[]
newSection[0][target.property] = value;

為什么它說Property 'type' does not exist on type 'Skill | Experience | Education | Language'. Property 'type' does not exist on type 'Skill | Experience | Education | Language'. 如果它已經知道newSectionstate.skills並且那里存在屬性type

您已將 object 拆分為獨立的局部變量,因此類型之間不再存在鏈接。 檢查局部變量section的類型對target的類型沒有影響。 你和我也許能夠看到這種關系,但是 typescript 沒有能力回溯以找出類型是如何產生的,然后計算對其他變量的所有后果

要縮小target類型,您需要檢查target上的屬性,如下所示:

if (target.section === 'skills') {
  // now the type on target has been narrowed
  console.log(target.foobar)
}

盡管我相信您會遇到另一個問題,即該section並未出現在您的聯合中的所有可能類型上,因此 typescript 不會讓您訪問target.section 因此,您需要:

if ('section' in target && target.section === 'skills) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM