我有一个函数可以发送请求以使用单个输入道具创建和编辑待办事项。我想输入此函数的输入以仅接受CreateTodoInput
或EditTodoInput
export interface ICreateTodoInput {
todoName: string;
todoType: TodoType;
todoContent:string;
todoCompletionStatus: TodoCompletionStatus;
}
export interface IEditTodoInput {
todoId: string;
todoName?: string;
todoType?: TodoType;
todoContent?: string;
todoCompletionStatus?: TodoCompletionStatus;
}
//(the `Todo...` types are just string enums)
编辑:我试过了,ICreateTodoInput | IEditTodoInput
但这是两种类型的结合,会出错Property 'todoId' does not exist on type 'ICreateTodoInput'
文档提到了条件类型,这听起来像我想要的,但不确定如何将其添加到我的反应组件中
type EitherOr<T> = T extends ICreateTodoInput
? ICreateTodoInput
: IEditTodoInput;//will this work?
有问题的组件
interface ITodoMutatorProps{
todoInput?: //<-- want to type this
}
export const TodoMutator = ({
todoInput
}: ITodoMutatorProps): JSX.Element => {
//if todoInput is type ICreateTodoInput
//send create request
//if todoInput is type IEditTodoInput
//send edit request
}
我不会在这里推荐条件类型。你所面对的是一个“受歧视的工会”。您有一个类型,可以是 anICreateTodoInput
或 an,IEditTodoInput
并且您需要知道它是哪一种,然后才能将其用于创建或编辑操作。
区分这两种类型的最简单方法是查找todoId
存在于 中IEditTodoInput
但不存在于 中的属性ICreateTodoInput
。TypeScript 知道如果这个属性存在,那么你的todoInput
变量就是一个IEditTodoInput
.
编辑:我尝试过 ICreateTodoInput | IEditTodoInput 但这是两种类型的联合,并且会出现错误属性 'todoId' 在类型 'ICreateTodoInput' 上不存在
您不能访问联合类型的属性,除非它在联合的所有分支中声明。但是您可以 使用in
运算符来缩小类型。
interface ITodoMutatorProps {
todoInput: ICreateTodoInput | IEditTodoInput;
}
export const TodoMutator = ({
todoInput
}: ITodoMutatorProps): JSX.Element => {
if ("todoId" in todoInput) {
editTodo(todoInput);
}
else {
createTodo(todoInput);
}
完整代码(枚举和函数的占位符为空):
enum TodoCompletionStatus { }
enum TodoType { }
function editTodo(input: IEditTodoInput) { }
function createTodo(input: ICreateTodoInput) { }
export interface ICreateTodoInput {
todoName: string;
todoType: TodoType;
todoContent: string;
todoCompletionStatus: TodoCompletionStatus;
}
export interface IEditTodoInput {
todoId: string;
todoName?: string;
todoType?: TodoType;
todoContent?: string;
todoCompletionStatus?: TodoCompletionStatus;
}
interface ITodoMutatorProps {
todoInput: ICreateTodoInput | IEditTodoInput;
}
export const TodoMutator = ({
todoInput
}: ITodoMutatorProps): JSX.Element => {
if ("todoId" in todoInput) {
//todoInput is type IEditTodoInput
//send edit request
editTodo(todoInput);
}
else {
//todoInput is type ICreateTodoInput
//send create request
createTodo(todoInput);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句