首页 > 解决方案 > object foo 有两个 props bar 和 baz ,如何通过 bar 的值推断 baz 类型

问题描述

type OneType = {a: string};
type TwoType = {b: number};
type DefineItem = {
   bar: 'one' | 'two',
   baz: OneType | TwoType
};

const items: DefineItem = {
  bar: 'one',
  baz: ???
}

预计:

当 bar === 'one' 时,推断 baz 的类型是 OneType

当 bar === 'two' 时,推断 baz 的类型是 TwoType

标签: typescripttypescript-typings

解决方案


您可以定义两种类型的有区别的联合:

type OneType = {a: string};
type TwoType = { b: number };

type DefineItem = {
    bar: 'one',
    baz: OneType
} | {
    bar: 'two',
    baz: TwoType
};

const item1: DefineItem = {
    bar: 'one',
    baz: { a: 'hello' }
}

const item2: DefineItem = {
    bar: 'two',
    baz: { b: 5 }
}

请参阅此TypeScript Playground


推荐阅读