簡體   English   中英

如何像流一樣在 Typescript 中定義條件字符串類型?

[英]How to define conditional string types in Typescript like flow?

type UpsertMode = | 'add' | 'update' | 'delete';

interface IUpsertMembers {
  mode: UpsertMode;
}

const MagicButton = ({ mode: UpsertMode }) => {
  return (
    <button>{mode}</button>
  );
}

const UpsertMembers = ({ mode }: IUpsertMembers) => {
  return (
    <MagicButton mode={mode} />
  );
};

export default UpsertMembers;

我試圖在.tsx file使用它,但類型仍然是any

它給出了一個錯誤說

Binding element 'UpsertMode' implicitly has an 'any' type.  TS7031

嘗試刪除初始 |

type UpsertMode = add' | 'update' | 'delete';

看起來您的問題出在mode變量的綁定上。 您希望MagicButton采用{mode: UpsertMode}類型的單個參數,然后將其解構為名為mode的函數局部變量。 要做到這一點,你必須這樣寫:

const MagicButton = ({ mode }: { mode: UpsertMode }) => {
  return (
    <button>{ mode } < /button>
  );
}

這與您在UpsertMembers函數中的注釋基本相同。


({ mode: UpsertMode }) => ...不起作用的原因是因為那只是 JavaScript 而你沒有類型注釋。 它類似於({ mode: UpsertMode }: any) => ... 在這里, {mode : UpsertMode}正在執行一個對象解構,您可以在其中分配一個新變量 name 這意味着輸入的mode屬性已被解構為名為UpsertMode的函數局部變量。 不是您的意圖,並導致至少兩個有趣的錯誤:

  • 由於您沒有類型注釋, ({mode: UpsertMode})UpsertMode類型被隱式推斷為any ,這是--noImplicitAny的錯誤: Binding element 'UpsertMode' implicitly has an 'any' type.

  • 由於該函數沒有名為mode局部變量,您在函數中使用mode是一個錯誤: Cannot find name 'mode'.


如果您認為不必為了同時獲得解構賦值綁定和類型注釋而必須編寫mode兩次,那么您並不孤單。 有一個未解決的問題microsoft/TypeScript#29526 ,其中建議允許諸如({mode :: UpsertMode}) => ...來指示UpsertMode是一種類型而不是變量名。 如果您想增加發生這種情況的機會,您可能需要轉到該問題並給它一個 👍。


好的,希望有幫助; 祝你好運!

Playground 鏈接到代碼

暫無
暫無

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

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