我可以声明类型关联数组,然后将其用作键对象类型吗?

问题描述 投票:0回答:1

所以,我有这样一个关联数组结构:

type CellT = { name: string; value: number };
type AssociativeArrayT = {
    [key: string]: CellT[] | AssociativeArrayT;
};

const myObject: AssociativeArrayT = {
    key1: {
        subKey1: [
            { name: 'SomeName1', value: 100 },
            { name: 'SomeName2', value: 100 },
        ],
    },
    key2: [
        { name: 'SomeName3', value: 300 },
        { name: 'SomeName4', value: 400 },
    ],
};

我会使用这种类型(AssociativeArrayT)在声明新对象时检查道具。

主要问题是,在常量初始化后,如:“myObject:AssociativeArrayT”= {...},我无法通过键获取对象属性(当然,因为我已将 AssociativeArrayT 的键描述为字符串)。你能帮我吗,也许有一些简单的方法来获取以这种方式声明的键类型对象?

typescript object associative-array
1个回答
0
投票

这就是

satisfies
的作用。请参阅文档:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html

不要设置值的类型,而是说这个值

satisfies AssociativeArrayT
,这意味着可以推断出更具体的子类型。

所以:

const myObject = {
    key1: {
        subKey1: [
            { name: 'SomeName1', value: 100 },
            { name: 'SomeName2', value: 100 },
        ],
    },
    key2: [
        { name: 'SomeName3', value: 300 },
        { name: 'SomeName4', value: 400 },
    ],
} satisfies AssociativeArrayT;

其中有您期望的类型:

type Test1 = keyof typeof myObject
// 'key1' | 'key2'

type Test2 = keyof typeof myObject['key1']
// 'subKey1'

看游乐场

© www.soinside.com 2019 - 2024. All rights reserved.