[英]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
是一種類型而不是變量名。 如果您想增加發生這種情況的機會,您可能需要轉到該問題並給它一個 👍。
好的,希望有幫助; 祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.