Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

接口响应数据对象的类型限定问题。响应数据中有一个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,如何动态限定?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...