const enum ColumnValues {
one = 1,
two = 2,
three = 3,
}
interface Props {
style?: StyleProp<ViewStyle>;
title?: string;
titleContainerStyle?: StyleProp<ViewStyle>;
titleStyle?: StyleProp<TextStyle>;
textInputStyle?: StyleProp<TextStyle>;
column?: ColumnValues.one | ColumnValues.two | ColumnValues.three;
}
const DynPut: FC<Props> = Props => {
...
return(
...
)
我已將此 DynPut 匯入另一個組件并將值 10 傳遞給 Column Prop,但 typescript 沒有拋出任何錯誤。當任何大于 3 的值傳遞給 Column Prop 時,如何使打字稿拋出錯誤
<DynPut
title="Add Items"
style={{backgroundColor: 'yellow'}}
titleStyle={{backgroundColor: 'green'}}
titleContainerStyle={{backgroundColor: 'green'}}
textInputStyle={{borderWidth: 5}}
column={10}
/>
uj5u.com熱心網友回復:
這與此問題非常相似,但是應稍微修改先前的答案以適應此問題。如果您認為它是重復的,請隨時標記它。
這里的主要問題是number打字稿中的型別可以分配給數字列舉,即使它不符合列舉值/要求。請參閱此答案以獲取更多背景關系。
為了驗證提供的數字,我們需要對所有列舉數字和提供的column數字進行字串化。然后驗證它們是安全的。
考慮這個例子:
enum ColumnValues {
one = 1,
two = 2,
three = 3,
}
// Stringifies each enum numeric value.
// Example: 3 -> "3"
type Enumerate<Enum> = Enum extends number | string ? keyof {
[Prop in `${Enum}`]: Prop
} : never
// Obtain stringified enum values
type Result = Enumerate<ColumnValues> // "0" | "1"
// Obtain a union of object values
type Values<T> = T[keyof T]
// Check whether provided initial value extends stringifiedn enum value
// if yes - allow this value and return initial
// id no - return never, so TS with throe an error
type IsKeyValid<InitialValue extends number, Enum> =
`${InitialValue}` extends Enumerate<Enum> ? InitialValue : never
type Props<Count extends number> = {
column: IsKeyValid<Count, ColumnValues>
}
const DynPut = <Count extends number>(props: Props<Count>) => { }
DynPut({ column: 1 }) // ok
DynPut({ column: 5 }) // error
操場
另請參閱我的文章
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371422.html
