typescript type with a specific set of keys and values

I don’t think you can do this with interfaces: the ‘extends’ always means you can extend. However how about what’s below? It’s a little clunky since we’re defining our new type inside <>, but I think it does what you want.

type AllowedKeys = "a" | "b" | "c";

type MyGenericType<T extends AllowedKeys> = {
    type: T;
}

type MyObjectTypeGuard = { [T in AllowedKeys]: MyGenericType<T> };

type VerifyType<T extends MyObjectTypeGuard &
    { [U in Exclude<keyof T, AllowedKeys>]: never }> = T;

// Incorrect type letters or missing 'type', additional properties,
// and missing properties lead to errors
type VerifiedType = VerifyType<{
    a: { type: "a" } & { foo: "foo" };
    b: { type: "b" } & { bar: "bar" };
    c: { type: "c" } & { baz: "baz" };
}>;

const obj: VerifiedType = {
    a: { type: "a", foo: "foo" },
    b: { type: "b", bar: "bar" },
    c: { type: "c", baz: "baz" }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top