ar099968
ar099968

Reputation: 7537

Typescript: property type based on property value

It's possible set a property type based on property value?

An example, if command is:

Now the closest solution i found is:

export interface Command {
    command: 'set' | 'put' | 'del';
    payload: PayloadSet | PayloadPut | PayloadDel;
}

but this allow user to set a command and set a wrong payload

Upvotes: 1

Views: 83

Answers (2)

user11534547
user11534547

Reputation:

You can do some fancy stuff with conditional types, by adding a generic to the Command interface:

interface PayloadDel { }
interface PayloadPut {}
interface PayloadSet {}

type Commands = 'set' | 'put' | 'del'
export interface Command<K extends Commands> {
    command: K;
    payload: K extends 'set' ? PayloadSet : K extends 'put' ? PayloadPut : PayloadDel;
}

let command: Command<'set'>

This way the type depends on the type of K

Upvotes: 0

zerkms
zerkms

Reputation: 254916

Design it as a union:

type Command =
    | { command: 'set'; payload: PayloadSet; } 
    | { command: 'put'; payload: PayloadPut; } 
    | { command: 'del'; payload: PayloadDel; } 

Upvotes: 3

Related Questions