简体   繁体   English

基于字段值的打字稿条件类型

[英]Typescript conditional type based on value of a field

How do you strongly type your json when you have the following structure:当您具有以下结构时,您如何强输入 json:

{
 type:"A",
 query:[]  
}

The above could be strongly typed in following manner:上述内容可以按以下方式强类型:

export class Schema {
    constructor() { }
    type: string;    
    query: []
}

create(schema:Schema){}// strongly typed json

But query property will always be array but the items could differ greatly.但是查询属性将始终是数组,但项目可能会有很大差异。

For example.例如。

If type == "typeA"

query property will have something like:
  query: ["","",""] //structure fixed for typeA

If type == "typeB"

query property will have something like:
  query: [{name:"",phone:1234}] //structure fixed for typeB

If type == "typeC"

query property will have something like:
  `query: ["",[{city:""}]]` //structure fixed for typeC

Something like this ? 像这样的东西?

const enum DataType {
  TypeArray = "A",
  TypePhone = "B",
  TypeCity = "C",
  // and so on
}

interface DataArray {
  type: DataType.TypeArray;
  query: any[]
}

interface DataPhone {
  type: DataType.TypePhone;
  query: {
    name: string,
    phone: string
  }
}

interface DataCity {
  type: DataType.TypeCity;
  query: {
    city: {name: string, location: string}
  }
}

type JsonData = DataArray | DataCity | DataPhone;

// Test area
function getSomething(): JsonData {
  return {type: DataType.TypePhone, query: {name: 'Hello', phone: 'World'}}
}
let x: JsonData = getSomething();
if (x.type == DataType.TypeCity) {
  console.log(x.query.city);
}

像这样的东西?

public setSelectedValues(val: number | number[] | string | string[]): void {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM