流类型别名
当仅以文字形式书写时,Flow 很快就会变得非常冗长。将重复的类型声明为类型别名通常很有用。
声明类型别名
假设你正在编写函数来操作待办事项列表:
// Add a new todo item to `todos` and return the new item.
function addTodo(
todos: Array<{id: number, name: string, completed: boolean}>,
name: string,
): {id: number, name: string, completed: boolean} {
// Implementation omitted for brevity.
}
// Get a todo item from `todos` by `id`.
function getTodo(
todos: Array<{id: number, name: string, completed: boolean}>,
id: number,
): {id: number, name: string, completed: boolean} {
// Implementation omitted for brevity.
}
// Get all incomplete todo items in `todos`.
function getIncompleteTodos(
todos: Array<{id: number, name: string, completed: boolean}>,
): Array<{
id: number,
name: string,
completed: boolean,
}> {
// Implementation omitted for brevity.
}
您可能注意到{id: number, name: string, completed: boolean}
被重复了很多次。除了非常冗长之外,这还有其他问题;如果您想在待办事项中添加一些内容(dateCompleted、assignedTo 等),您必须编辑 的每个实例{id: number, name: string, completed: boolean}
,这很繁琐且容易出错。
因此,我们将其别名为自己的类型TodoItem
。这很简单,就像声明一个变量一样:
type TodoItem = {id: number, name: string, completed: boolean};
从那里,您可以TodoItem
像使用任何其他类型一样使用它。
// The type alias.
type TodoItem = {id: number, name: string, completed: boolean};
// Add a new todo item to `todos` and return the new item.
function addTodo(todos: Array<TodoItem>, name: string): TodoItem {
// Implementation omitted for brevity.
}
// Get a todo item from `todos` by `id`.
function getTodo(todos: Array<TodoItem>, id: number): TodoItem {
// Implementation omitted for brevity.
}
// Get all incomplete todo items in `todos`.
function getIncompleteTodos(todos: Array<TodoItem>): Array<TodoItem> {
// Implementation omitted for brevity.
}
导出类型别名
TodoItem
也可以在其他文件中使用。只需将其标记为导出即可,如下所示:
// todos.js
export type TodoItem = {id: number, name: string, completed: boolean};
// someOtherFile.js
import type {TodoItem} from './todos';
function somethingThatTakesATodoItem(item: TodoItem): void {
}