繁体   English   中英

Typescript:如何通过推理定义object的键?

[英]Typescript: How do define keys of an object by inference?

我想在不输入的情况下定义嵌套的 object 的键。 我怎样才能让 typescript 只接受键“itemA”和“itemB”而不输入它(因为实际上有两个以上的键)?

// I don't want the key to be any string. It should be whatever is in the object so `itemA | itemB`.
// I also DO NOT want to define all keys myself since it's much longer than in this example
interface IMyObject {
    bucket1: Record<string, string>;
}

const myObject:IMyObject = {
    bucket1: {
        itemA: "itemA",
        itemB: "itemB",
    },
}

// This should be invalid
const itemC = myObject.bucket1.itemC;

这应该做的工作

// I don't want the key to be any string. It should be whatever is in the object so `itemA | itemB`.
// I also DO NOT want to define all keys myself since it's much longer than in this example
interface IMyObject<T> {
    bucket1: Record<keyof T, string>;
}

const bucket = {
        itemA: "itemA",
        itemB: "itemB",
    }
    
const myObject:IMyObject<typeof bucket> = {
    bucket1: bucket,
}

// This should be invalid
const itemC = myObject.bucket1.itemC;

要按要求回答问题,您根本不需要任何显式类型。 TypeScript 将根据 object 文字推断类型信息:

const myObject = {
    bucket1: {
        itemA: "itemA",
        itemB: "itemB",
    },
}

// This is invalid
const itemC = myObject.bucket1.itemC;

如果您的情况更复杂,请提供更多详细信息,以帮助我们了解您到底想做什么。

暂无
暂无

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

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