[英]Typescript - How to extends model with typescript interface
I have a tasks that have a common interface and some extensions:我有一个具有通用界面和一些扩展的任务:
export interface Task {
name: string;
id: number;
type: taskType
}
export enum taskType {
EVENT = 'EVENT',
NOTES = 'NOTES',
}
These are the extensions of Task:这些是任务的扩展:
export interface EventTask extends Task {
startDate: Date,
endDate: Date
}
export interface NotesTask extends Task {
description: string,
}
When I get the backend result I can get these array, data properties change based on type:当我得到后端结果时,我可以获得这些数组,数据属性会根据类型而变化:
[{id: 1, name: 'TaskNote1', type: 'NOTES', description: 'Hello world'}, {id: 2, name:
'TaskEvent1', type: 'EVENT', startDate: '2021-04-04', endDate: '2021-04-19'}];
How can Obtain these variable model into the Task interface?如何将这些变量 model 获取到 Task 界面中? I can't find a solution
我找不到解决方案
Your array is of type (NotesTask | EventTask)[]
.您的数组属于
(NotesTask | EventTask)[]
类型。 You can use Type Guards
to define the difference between them.您可以使用
Type Guards
来定义它们之间的区别。 A type guard is a function which rules out the possibility of a value being the wrong type.类型保护是 function,它排除了值是错误类型的可能性。
A type guard uses the is
operator to tell TypeScript which type is which.类型保护使用
is
运算符告诉 TypeScript 哪个类型是哪个。
For example:例如:
const isNotesTask = (task: NotesTask | EventTask): task is NotesTask => {
return task.type === taskType.NOTES
}
const isEventTask = (task: NotesTask | EventTask): task is EventTask => {
return task.type === taskType.EVENT
}
You can use this in an if
statement like this:您可以在这样的
if
语句中使用它:
// Outside the if statement task is of type NotesTask | EventTask.
if (isNotesTask(task)) {
// In here task is of type NotesTask
}
if (isEventTask(task)) {
// In here task is of type EventTask
}
The other answer good, but I find it to have more boilerplate and be less robust than the following solution:另一个答案很好,但我发现它比以下解决方案有更多的样板并且不那么健壮:
interface CommonTaskProperties {
name: string;
id: number;
}
export type Task =
| {type: 'EVENT', startDate: Date, endDate: Date} & CommonTaskProperties
| {type: 'NOTES', description: string} & CommonTaskProperties
Then you can do this:然后你可以这样做:
const task: Task = {type: "NOTES", description: "This is a notes task."};
switch (task.type) {
case 'EVENT':
// Handle event task here
break;
case 'NOTES':
// Handle notes task here
break;
}
Inside each of the cases, the type will appropriately be inferred without having to use explicit type guards or assertions.在每种情况下,将适当地推断类型,而无需使用显式类型保护或断言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.