[英]How to type object which contains string keys and values are MUI SX prop type
[英]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} />
...
我有以下檢查類型的解決方案,但我不知道這是否是一個好習慣。
...
<Input name={((k: KForm)=>k)('email')} />
...
const getFieldName = (k: KForm) => k;
...
<Input name={getFieldName('email')} />
...
const emailField: KForm = 'email';
...
<Input name={emailField} />
...
interface WrapperInputProp extends InputProp {
name: KForm
}
...
<WrapperInput name={'email'} />
在我看來,選項 4 是最好的,其次是選項 3。這兩個選項都在編譯時提供 static 類型檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.