SamuraiJack
SamuraiJack

Reputation: 5539

Typescript conditional type based on value of a field

How do you strongly type your json when you have the following structure:

{
 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

Upvotes: 0

Views: 2457

Answers (2)

Anton
Anton

Reputation: 2703

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

Upvotes: 3

Sheldon Neilson
Sheldon Neilson

Reputation: 803

Something like this?

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

Upvotes: 0

Related Questions