Estoy tratando de generar una "clave de objeto dinámica" basada en un "valor de clave de apoyo" seleccionando un valor de clave de objeto específico.
Entonces, digamos que paso { name: 'someEntity', unrelatedKey: 123 } y me gustaría devolver { someEntity: 'ok' } . ¿Cómo se haría eso para que el valor de retorno esté definido por el tipo de mecanografiado? He intentado algo como esto pero no funciona:
type GetExampleProps = { name: string unrelatedKey: number } type GetExampleRes<T> = { [key: T]: string } function getExample<T extends GetExampleProps> (props: T): GetExampleRes<T['name']> { return { [props.name]: 'ok' } } const example = getExample({ name: 'someEntity', unrelatedKey: 123 }) example.someEntity // should be valid type string example.hello // should be invalid, missing keyActualmente no puedo hacer eso sin una afirmación de tipo, pero como solución temporal aquí está:
type GetExampleProps<T extends PropertyKey = string> = { name: T; unrelatedKey: number; }; function getExample<T extends PropertyKey>( props: GetExampleProps<T> ): { [K in T]: string; } { const toRet = { [props.name]: "a string", }; return toRet as { [K in T]: string }; } const example = getExample({ name: "someEntity", unrelatedKey: 123 }); example.someEntity; example.hello; // Property 'hello' does not exist on type '{ someEntity: string; }'Pruebe esta función, esto debería funcionar de la manera que necesita
const createObject = (obj: any) => { interface I { [name: string]: any; } const returnObj: I = {}; returnObj[obj.name] = Object.keys(obj).filter((key) => key !== "name"); return returnObj; };