簡體   English   中英

如何確保字符串是接受字符串的道具中 object 的鍵之一?

[英]How to ensure that string is one of the keys of an object in a prop that accepts string?

這是來自 package 的組件的流線型 prop 定義(我不控制)。

interface InputProps {
  name: string,
  value?: string
}

這是我的表單的流線型類型定義。

interface IForm {
  name: string,
  email: string,
}

type KForm = keyof IForm

這是我的代碼,我故意放了一個錯誤的字符串,但它沒有顯示錯誤。

...
 <Input name={'emailx' as KForm} />
...

我有以下檢查類型的解決方案,但我不知道這是否是一個好習慣。

  1. 自執行 function
...
 <Input name={((k: KForm)=>k)('email')} />
...
  1. 同上,但在別處分開。

const getFieldName = (k: KForm) => k;

...
 <Input name={getFieldName('email')} />
...
  1. 聲明單獨的變量。
const emailField: KForm = 'email';
...
 <Input name={emailField} />
...
  1. 一個包裝組件。
interface WrapperInputProp extends InputProp {
  name: KForm
}
...
<WrapperInput name={'email'} />

在我看來,選項 4 是最好的,其次是選項 3。這兩個選項都在編譯時提供 static 類型檢查。

暫無
暫無

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

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