【发布时间】:2021-12-08 16:59:25
【问题描述】:
我想要一个 TypeScript 对象字面量常量,其中包含已知但很长的属性列表,这些属性都具有相同的类型。下面是类型的定义和只有三个属性的简化示例。
type ContainerSize = {
height: string;
width: string;
threshold?: number;
};
const CONTAINER_SIZES = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
上面定义的问题是属性类型不是ContainerSize。这可以通过使用Record<string, ContainerSize> 作为对象类型来解决:
const CONTAINER_SIZES: Record<string, ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
但现在任何字符串都是有效的键,因此CONTAINER_SIZES['not-existing'] 不会显示错误。
除了像下面的示例那样两次写入属性之外,还有其他方法来定义对象字面量吗?
const CONTAINER_SIZES: Record<'/' | '/info' | 'default', ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
【问题讨论】:
-
为什么你希望属性值为
ContainerSize,具体来说?我猜这是为了开发者体验,但有什么具体的吗? -
是的,它是为了开发者体验。如果某个函数参数类型是
ContainerSize,最好从CONTAINER_SIZES中立即看到它具有正确的属性类型,而不是检查它们是否匹配。
标签: typescript