Home > Enterprise >  Typescript how to say two value will be same type but they could be anything
Typescript how to say two value will be same type but they could be anything

Time:07-23

My question is for example there is a interface like this

interface Example {
value: any;
otherValueToCompare: any;
}

They could be anything, but they should be same type. If someone tries to send a string for value, otherValueToCompare's type should be string too.

How can it achieved?

CodePudding user response:

You can use generic types to achieve this:

type Example<T> = {
    value: T;
    otherValueToCompare: T;
}

const s: Example<string> = {
    value: 'x',
    otherValueToCompare: 'y'
}

const p: Example<number> = {
    value: 1,
    otherValueToCompare: 2
}
  • Related