有没有一种方法可以编写一个定义标准js对象类型的index.d.ts声明文件类型



假设我有一个变量

const obj = {
a: {
'b': 1,
},
c: {
'd': 2,
'e': 'hello',
}
}

我想要一个定义为Record<'a' | 'b', typeof a object (i.e Record<'b', number>) | type of b object (i.e. Record<'d' | 'e', number | string>) >的类型。在typescript中有没有一种简单的方法可以做到这一点,以便自动推断?

如果在TypeScript中声明此对象,它将推断出以下类型:

type TypeofObj = {
a: {
b: number;
};
c: {
d: number;
e: string;
};
};

如果你想要一个更像这样的字符串类型:

type TypeofObj = {
a: {
b: 1;
};
c: {
d: 2;
e: "hello";
};
};

将对象定义为const,如下所示:

const obj = {
a: {
'b': 1,
},
c: {
'd': 2,
'e': 'hello',
}
} as const;

最新更新