【发布时间】:2019-06-16 18:28:49
【问题描述】:
使用[key: string] 将使我的类型接受任何键。我试图避免它,因为在某些地方我重新定义了属性的类型。考虑关注。
interface IObject {
[K: string]: number;
}
const base: IObject = {
title: 0,
age: 3
};
type StringValue<T> = { [K in keyof T]: string }; // <-- How to remove object index
const child: StringValue<typeof base> = {
test: "" // <-- should not be possible
title: '' // <-- this is OK
};
【问题讨论】:
-
如果
base不允许任意键,而只允许title和age,那么它就不是IObject。为什么要宣布它为一个?另外,StringValue<T>的目的是什么? (不是我的反对票) -
根据建议的命名进行了更新。在简单的示例中,这不是问题。但是在像
base = { title: { value: '', valid: () => true }}这样的复杂结构中,我想确保在值和另一个接口之间建立契约。IObject { [K: string]: IProperty }
标签: typescript generics types interface typescript2.0