编程技巧
·70 words·1 min
Table of Contents
代数数据类型ADT #
type Props = {
name: string
} & (
{
gender: 'male';
salary: number
}
|
{
gender: 'female',
weight: number
}
)
这样可以动态地根据gender
来决定下一个需要的属性是salary
还是weight
。
type ApiResponse<T> =
| {status: 'success'; data: T; timestamp: Date}
| {status: 'error'; message: string; timestamp: Date}
let response1: ApiResponse<number> = {
status: 'success',
data: 100,
timestamp: new Date()
};
let response2: ApiResponse<number> = {
status: 'error',
message: 'error la',
timestamp: new Date()
};