考察如下场景:
即 appearence 属性是否通过 TypeScript 的类型检查依赖于 type 的值,请问组件的属性类型如何定义。 一开始会以为这里需要借助泛型等手段来构造一个复杂类型,其实大可不必。因为后来一想不防用 Union Types 试试,实践后证实,事情其实没想的那么复杂。 类型定义: type SelectProps = | { type: "native"; } | { type: "simulate"; appearance: "default" | "link" | "button"; }; 使用: function CustomSelect(props: SelectProps) { return <div>...</div>;}function App() { return ( <> {/* ✅ */} <CustomSelect type="native" /> {/* ❌ Type '{ type: "native"; appearance: string; }' is not assignable to type 'IntrinsicAttributes & SelectProps'. Property 'appearance' does not exist on type 'IntrinsicAttributes & { type: "native"; }'. */} <CustomSelect type="native" appearance="button" /> {/* ❌ Type '{ type: "simulate"; }' is not assignable to type 'IntrinsicAttributes & SelectProps'. Property 'appearance' is missing in type '{ type: "simulate"; }' but required in type '{ type: "simulate"; appearance: "default" | "link" | "button"; }'. */} <CustomSelect type="simulate" /> {/* ✅ */} <CustomSelect type="simulate" appearance="button" /> </> );} |
The text was updated successfully, but these errors were encountered: |
TypeScript + React 组件属性之间的依赖
转载文章标签 TypeScript React 文章分类 TypeScript 前端开发
-
React+TypeScript项目中如何使用CodeMirror?
之前做需求用到过codeMirror这个工具,觉得还不错,功能很强大,所以
react.js typescript 前端 css 代码提示 -
React + TypeScript
欢迎关注前端早茶,与广东靓仔携手共同进阶 前端早茶专注前端,一起结伴同行,紧跟业界发展步伐~ 一、前言 在R
html typescript 显式 -
TypeScript with React
TypeScript with React
TypeScript React parcel typescript html