I wrote a function that returns a helper method based on a record type or the default helper if it's undefined, but ts complains about it. Is it possible to fix it without defining every member of Types
? I didn't want to use if / switch
type Types = 'foo' | 'bar' | 'baz';
const fooHelper = () => console.log('fooHelper');
const getHelper = (t: Types) => {
const defaultHelper = () => console.log(t);
// Property 'bar' does not exist on type '{ foo: () => void; }'.ts(2339)
// Property 'baz' does not exist on type '{ foo: () => void; }'.ts(2339)
const { [t]: helper = defaultHelper } = {
foo: fooHelper,
};
return helper;
};
CodePudding user response:
You'll need set the type of your object as having all the keys as optional :
type SomeTypes = { [P in Types]?: unknown }
Which gives us this :
type Types = 'foo' | 'bar' | 'baz';
type SomeTypes = { [P in Types]?: unknown }
const fooHelper = () => console.log('fooHelper');
const getHelper = (t: Types) => {
const defaultHelper = () => console.log(t);
const someTypes: SomeTypes = { foo: fooHelper };
const { [t]: helper = defaultHelper } = someTypes;
return helper;
};