[英]Is there a way to write an index.d.ts declaration file type that defines a type of a standard js object?
假设我有一个变量
const obj = {
a: {
'b': 1,
},
c: {
'd': 2,
'e': 'hello',
}
}
我想要一个定义为Record<'a' | 'b', typeof a object (ie Record<'b', number>) | type of b object (ie Record<'d' | 'e', number | string>) >
Record<'a' | 'b', typeof a object (ie Record<'b', number>) | type of b object (ie Record<'d' | 'e', number | string>) >
Record<'a' | 'b', typeof a object (ie Record<'b', number>) | type of b object (ie Record<'d' | 'e', number | string>) >
是否有一种简单的方法可以在打字稿中做到这一点,以便自动推断?
如果在 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.