繁体   English   中英

Typescript - 如何使值等于 object 的键?

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

我想键入一个键和值相同的 object:

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

我尝试使用myObj设置typeof ,并使用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
}

有没有办法可以确保键和值始终匹配? 蒂亚!

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 游乐场链接

玩了一会儿就明白了:

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

使用此设置,我收到以下错误:

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

以下是让它快乐的原因:

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

更新:如果您有一个已知的键列表,则此方法有效,但如果您有一个未知的键列表或将任何键与其值匹配,请按照@sno2 的回答

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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