0

I'm trying to figure correct way to map Interface record value types to correct function type.

function stringCompose(): string {
    return ''
}
function numberCompose(): number {
    return 0
}

interface Demo {
    stringVal: string;
    numberVal: number;
}
// mapping type something like <T = any> = (() => T)
type ComposeMapper<T = any> = any;

const builder: ComposeMapper<Demo> = ({
    stringVal: stringCompose,
    numberVal: numberCompose,
});

So idea is that when creating builder it check that all Interface keys are in place and someway also do value mappings like Interface "string" => requires "() => string" which compose functions should be filling. Before I did similar setup, but there was tons of never checks and performance was really bad to solve those so I think there should be much easier way actually to do this.

1 Answer 1

1

It seems like you need to create mapped type from the interface.

TS Playground link

function stringCompose(): string {
    return ''
}
function numberCompose(): number {
    return 0
}

interface Demo {
    stringVal: string;
    numberVal: number;
}

type ComposeMapper<T> = {
    [K in keyof T]: () =>  T[K]
}

// OK
const builder: ComposeMapper<Demo> = ({
    stringVal: stringCompose,
    numberVal: numberCompose,
});

// Error
const builder1: ComposeMapper<Demo> = ({
//    ~~~~~~~~ Property 'numberVal' is missing in type '{ stringVal: () => string; }' but required in type 'ComposeMapper<Demo>'.(2741)
    stringVal: stringCompose,
});


// Error
const builder2: ComposeMapper<Demo> = ({
    stringVal: numberCompose,
//  ~~~~~~~~~ Type '() => number' is not assignable to type '() => string'.
    numberVal: numberCompose,
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.