Quiero escribir un objeto donde la clave y el valor sean los mismos:
const myObj = { FOO: 'FOO', BAR: 'BAR' }; Intenté configurar typeof con myObj y con la key :
const actions: { [x: string]: x } = { // 'x' refers to a value, but is being used as a type here. Did you mean 'typeof x'? set: 'set1' } const actions: { [x: string]: typeof x } = { set: 'set1' // doesn't trigger } const actions: { [p: string]: keyof typeof actions } = { set: 'set' // Type 'string' is not assignable to type 'never'. } type K = 'set' | 'set2'; const actions: { [p in K]: K } = { // triggers missing set2 set: 'set1' // doesn't trigger }¿Hay alguna manera de asegurarme de que la clave y el valor coincidan todo el tiempo? ¡TIA!
Puede hacer esto creando una función de ayuda que tome su objeto y luego haga una verificación de TypeScript generando parámetros adicionales que harían que su código fallara si el objeto dado no pasa nuestra misma ley de clave/valor.
// basically, we create an extra parameter when the object is not valid function createSamePairedObject<T extends Readonly<Record<PropertyKey, PropertyKey>>>(obj: T, ..._lockParams: T extends { [K in keyof T]: K } ? [] : ["INVALID_PAIRED_OBJECT"]): T { return obj as any; } // PASS const a = createSamePairedObject({ // { readonly a: "a" } a: "a", } as const); // FAIL - "b" != "bb" const b = createSamePairedObject({ a: "a", b: "bb", } as const); // FAIL - not const object const c = createSamePairedObject({ [5]: 5, }); // PASS const d = createSamePairedObject({ [5]: 5, } as const);Lo conseguí después de jugar con un rato:
type K = 'set' | 'set2'; const actions: { [p in K]: p } = { // note that I am using p instead of K from the question set: 'set1' }Con esta configuración me sale los siguientes errores:
TS2741: Property 'set2' is missing in type '{ set: "set"; }' but required in type '{ set: "set"; set2: "set2"; }'. TS2322: Type '"set1"' is not assignable to type '"set"'.Y lo siguiente es lo que lo hace feliz:
type K = 'set' | 'set2'; const actions: { [p in K]: p } = { set: 'set', set2: 'set2' }ACTUALIZACIÓN: Esto funciona si tiene una lista conocida de claves, pero si tiene una lista desconocida de claves o para hacer coincidir cualquier clave con su valor, siga la respuesta de @ sno2