typescript discriminated union type



Discriminated union - what this means is you get to say i want certain properties if my type is defined in a certain way.

// discriminated union

interface IPizza {
foodtype : 'pizza'
crust : string
}

interface ISandwich {
foodtype : 'sandwich'
bread : string
}

type Food = IPizza | ISandwich


const myfood : Food = {
foodtype : 'pizza',
crust : 'thin'
}

const sandwich : Food = {
foodtype : 'sandwich',
bread : 'wholemeal'
}



If i tried to define foodtype that is of 'pizza' to contain 'bread' property, i will get an error



const myfood : Food = {
foodtype : 'pizza',
bread : 'thin' // error
}

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm