接口响应数据对象的类型限定问题。响应数据中有一个type字段,取不同值时使另一个字段采用不同的类型

目前是这么写的:

interface ContentA {
  name: string;
  age: number;
}

interface ContentB {
  name: string;
  hobby: string;
}

// 接口响应数据的类型
interface ResponseData {
  type: '0' | '1';
  content: ContentA | ContentB;
}

当type为0时,希望content是ContentA,为1时是ContentB,如何动态限定?

阅读 1.8k
1 个回答

如果只有两种情况的话,可以这样写并且很简单易懂。

interface ResponseData1 {
    type: '0';
    content: ContentA;
}

interface ResponseData2 {
    type: '1';
    content: ContentB;
}

type ResponseData = ResponseData1 | ResponseData2;

const data: ResponseData = {
    type: '0',
    content: {
        name: 'xxx',
        hobby: 'xxx', // error
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进