Leanote's Blog
I love Leanote!
Toggle navigation
Leanote's Blog
Home
Chrome
Git
Linux
Windows
Others
工具大全
VsCode
Expo
Html
JavaScript
Npm
Node
Mock
React-Native
React
TypeScript
小程序
插件
正则
Dva
Ant-Design-React
Umi
Vue
Vux
Ant-Design-Vue
Http
Java
flutter
开发小工具
About Me
Archives
Tags
用ts定义一个属性二选一的对象
2022-12-24 12:19:50
116
0
0
admin
### 定义了一个 EitherOr 的类型来处理这种情况 ``` type FilterOptional<T> = Pick< T, Exclude< { [K in keyof T]: T extends Record<K, T[K]> ? K : never }[keyof T], undefined > > type FilterNotOptional<T> = Pick< T, Exclude< { [K in keyof T]: T extends Record<K, T[K]> ? never : K }[keyof T], undefined > > type PartialEither<T, K extends keyof any> = { [P in Exclude<keyof FilterOptional<T>, K>]-?: T[P] } & { [P in Exclude<keyof FilterNotOptional<T>, K>]?: T[P] } & { [P in Extract<keyof T, K>]?: undefined } type Objects = { [name: string]: any } type EitherOr<O extends Objects, L extends string, R extends string> = ( | PartialEither<Pick<O, L | R>, L> | PartialEither<Pick<O, L | R>, R> ) & Omit<O, L | R> ``` ### 使用例子 ``` // a、b二选一,并且必须传递一个 type RequireOne = EitherOr< { a: number; b: string; }, 'a', 'b' >; // a、b二选一,或者都不传 type RequireOneOrEmpty = EitherOr< { a?: number; b?: string; }, 'a', 'b' >; ``` ### 实际应用 ``` interface IColumn { title: string; dataIndex: string; render: () => React.ReactNode; } // 熟悉 antd 的同学应该都知道,如果传递了 render 的话,其他 dataIndex 其实就没意义 // 换个角度来说,其实它们两个是“二选一”的属性 interface ITableProps { columns: Array< EitherOr< IColumn, 'dataIndex', 'render' > >; } function Table(props: ITableProps){ // TODO } ```
Pre:
.d.ts声明问题
Next:
TS中interface和type的区别
0
likes
116
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.