【问题标题】:Typescript: Constraint on a field of an union type打字稿:联合类型字段的约束
【发布时间】:2021-10-04 22:52:42
【问题描述】:

我创建了一个联合类型的对象。它们都有一个字段role 来区分它们。 这里有老师学生

type User =
    {
        role: "student";
        followClasses: string[];
    } |
    {
        role: "teacher";
        since: number;
    };

然后我想创建一个函数来生成一个默认学生

const defaultStudent = (): User => ({
    role: "student",
    followClasses: [],
});

但是由于返回类型是联合类型User,typescript不知道是学生抛出当我输入以下内容时,我会收到警告

const student = defaultStudent();

console.log(student.followClasses);
//          Warning here ⮥

如何让函数defaultStudent有一个受约束的返回类型(学生)?

【问题讨论】:

    标签: typescript types constraints field union


    【解决方案1】:

    将联合的两个成员提取为单独的类型

    type Student = {
      role: "student"
      followClasses: string[]
    }
    
    type Teacher = {
      role: "teacher"
      since: number
    }
    

    并直接从他们那里定义你的联合

    type User = Student | Teacher
    

    此时,您可以说您的defaultStudent 函数不仅返回User,还可以更精确。它返回一个Student

    const defaultStudent = (): Student => ({
      role: "student",
      followClasses: [],
    })
    
    const student = defaultStudent()
    console.log(student.followClasses) // <-- OK
    

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 2021-04-20
      • 2018-12-06
      • 2021-11-06
      • 2021-11-08
      • 2017-05-18
      • 2021-08-05
      • 2020-11-30
      相关资源
      最近更新 更多