如何从打字稿中的typeof对象中删除索引

How to remove index from typeof object in typescript

使用 [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
};

您不能真正做到这一点,因为一旦您将其显式键入 IObjectBase 就会丢失有关分配给它的内容的信息。 Base 不会在其类型中具有索引签名 属性 名称。 Base 的类型是 IObject,它是一个索引签名,仅此而已。

我的猜测是您想将 Base 限制为只有数字属性,但您想要捕获分配给它的对象文字的实际类型。单靠变量是做不到的,你需要使用一个额外的函数。函数可以具有受约束但基于实际参数推断的类型参数。

interface IObject {
    [K: string]: number;
}
function createObject<T extends IObject>(o: T) {
    return o;
}
const base = createObject({
    title: 0,
    age: 3
});
type StringValue<T> = { [K in keyof T]: string };  // <-- How to remove object index


const child: StringValue<typeof base> = {
    test: "", // <-- error
    title: '', // <-- this is OK
    age: ""
};