Search code examples
typescripttypesinterfacecompare

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


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?


Solution

  • 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
    }