简体   繁体   中英

Typescript - How to make values to equal the keys of an object?

I want to type an object where the key and value are the same:

const myObj = {
    FOO: 'FOO',
    BAR: 'BAR'
};

I tried setting up typeof with myObj , and with the 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
}

Is there a way I can make sure the key and value match all the time? TIA!

You can do this by creating a helper function that takes in your object then does a TypeScript check on it by generating extra parameters that would make your code fail if the given object does not pass our same key/value law.

// a helper type for equality
type Equal<T, F> = T extends F ? F extends T ? true : false : false;

// basically, we create an extra parameter when the object is not valid
function createSamePairedObject<T extends Readonly<Record<PropertyKey, PropertyKey>>>(obj: T, ..._lockParams: Equal<keyof T, T[keyof T]> extends true ? [] : ["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({ // { readonly 5: 5 }
  [5]: 5,
} as const);

TypeScript Playground Link

I got it after playing with for a while:

type K = 'set' | 'set2';
const actions: { [p in K]: p } = { // note that I am using p instead of K from the question
    set: 'set1'
}

With this setup I get the following errors:

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"'.

And following is what makes it happy:

type K = 'set' | 'set2';
const actions: { [p in K]: p } = {
    set: 'set',
    set2: 'set2'
}

UPDATE: This works if you have a known list of keys, but if you have an unknown list of keys or to match any key to its value, please follow @sno2 's answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM