#How to capturing the Exact Type of a Variable While Enforcing Interface Constraints

1 messages · Page 1 of 1 (latest)

upper python
#

Hello everyone,

I have a TypeScript question regarding the ability to capture the "exact type" of a variable that has been explicitly typed with an interface. Here's a quick example to illustrate:

interface ExampleInterface {
    example?: number,
    obj?: {
        innerExample?: boolean,
        somethingElse?: number | string
    }
}

const test: ExampleInterface = {
    example: 1,
    obj: { 
        innerExample: true
    }
}

type newTest = typeof test;

In the code above, newTest is inferred to be of type ExampleInterface. However, I'm interested in capturing the exact type of test, ie.

type newTest = {
    example: 1,
    obj: { 
        innerExample: true
    }
}

Removing the ExampleInterface type from test isn't ideal, as I'd lose IntelliSense and type checking.
I tried using a helper function to get around this limitation:

function ExampleInterface<T extends ExampleInterface>(example: T): T {
    return example;
}

const test = ExampleInterface({
    example: 1,
    obj: { 
        innerExample: true
    },
    thisShouldNotBeAllowed: true // But this should not be allowed
});

type newTest = typeof test;

While the helper function helps me capture the exact type I want for newTest, it also allows any properties that extend ExampleInterface. This is not what I'm aiming for.

So, is there a way to get the best of both worlds? I'd love to hear your thoughts and suggestions. Thank you in advance!

plain urchin
#

What you are looking for is satisfies.

proper badgeBOT
#
interface ExampleInterface {
    example?: number,
    obj?: {
        innerExample?: boolean,
        somethingElse?: number | string
    }
}

const test = {
    example: 1,
    obj: { 
        innerExample: true
    }
} satisfies ExampleInterface

test
//^? - const test: {
//    example: number;
//    obj: {
//        innerExample: true;
//    };
//}
upper python
#

Holy moly macaroni, my goooood, since when is that a thing?!?! I love it, thanks for enlightening me with this invaluable piece of TypeScript wizardry @plain urchin !