首页 > 解决方案 > F# 新类型是旧类型的扩展

问题描述

所以说我有一个员工类型

type employee = {
    employee_id: int
    name: string 
    department: int
}

type department = {
   department_id: int
   department_name: string
}

我想要第二种类型,它既包括员工类型中的所有内容,也包括部门类型中的所有内容(实际上是 SQL 连接的结果)。

例如

type employee_extended = {
    employee_id: int
    name: string 
    department: int
    department_id: int
    department_name: string
}

实际上,我有更多列的表,所以只是想知道是否有定义扩展类型的简写:) 可以假设属性名称没有重复,但如果可以处理它们,将来可能会有用。

标签: f#

解决方案


如果您有两种类型(员工和部门)的一些数据,并且想要创建一个包含有关员工和部门的信息的新类型,最好的方法是定义一个包含其他两种类型作为字段的新记录类型:

type Employee = {
    EmployeeId: int
    Name: string 
    Department: int
}

type Department = {
   DepartmentId: int
   Department_name: string
}

// New type containing information about 
// an employee and also their department
type EmployeeWithDepartment = {
  Employee : Employee
  Department : Department
}

推荐阅读