Considere dos interfaces Typescript A y B:
interface A { propertyA: string; propertyB: string; propertyC: string; propertyD: string; propertyE: string; } interface B { propertyF: string; propertyG: string; propertyH: string; propertyI: string; propertyJ: string; propertyK: string; }Quiero definir una constante, un par clave-valor, que empareja un valor de cadena con la interfaz A o la interfaz B.
const keyValuePair: { [key: string]: A | B} = {};Luego, una función pasaría un valor genérico, T, indicativo de cuál sería el valor en el par clave-valor, y devolvería el par clave-valor con el objeto de valor apropiado:
export async function getKeyValuePair<T>(keyId: string): Promise<T> { if (keyValuePair<T>[keyId]) { return keyValuePair<T>[keyId]; } }Obviamente. Lo anterior no funcionará. Pero, ¿cómo puedo hacer que funcione? Si solo estuviera haciendo la interfaz A, haría lo siguiente y funcionaría bien:
const keyValuePair: { [key: string]: A} = {}; export async function getKeyValuePair(keyId: string): Promise<A> { if (keyValuePair[keyId]) { return keyValuePair[keyId]; } }Me doy cuenta de que podría hacer lo siguiente:
const keyValuePair: { [key: string]: any} = {};Pero realmente quiero algo mejor y me gustaría evitar el uso de "cualquiera" si es posible. ¿Cómo haría esto?
Si su objetivo es recuperar un objeto y convertirlo en un tipo determinado, puede hacer esto:
export async function getKeyValuePair<T>(keyId: keyof T): Promise<T> { return keyValuePair[keyId] as unknown as T; }Así que podrías usar así:
getKeyValuePair<B>('propertyF');