我正在使用接口在Typescript中定义类型安全对象,并提供易于维护的代码结构。但是,在某些情况下,智能感知会被破坏。
当键未知并且仍要完成代码时,最好的方法是什么?
这是一个简单的例子,显示我的意思:
interface IObject {
name: string,
value: number
};
// here is the type safe collection interface
interface ICollection {
[key: string]: IObject
};
// ...
// here is the type safe collection
let collection: ICollection = {
a: {
name: "a",
value: 1
},
b: {
name: "b",
value: 2
}
};
// here is the type unsafe collection
let collection2 = {
a: {
name: "a",
value: 1
},
b: {
name: "b",
value: 2
},
c: {
key: 1,
status: true
}
};
// ...
console.log(collection2.a.value); // this works ok, but it's not type safe
console.log(collection.a.value); // this is type safe, but there is no more intellisense support
我认为您正在寻找此处描述的答案:https://stackoverflow.com/a/49630741/11005213
遵循这些原则:
interface IObject {
name: string;
value: number;
};
interface IUnsafeObject extends Partial<IObject> {
// if you know the type you can narrow it down here
// e.g. [key: string]: boolean | number
[key: string]: any;
}
interface ICollection<TType> {
[key: string]: TType
};
let collection: ICollection<IObject> = {
a: { name: "a", value: 1 },
b: { name: "b", value: 2 }
};
let collection2 : ICollection<IUnsafeObject> = {
a: { name: "a", value: 1 },
b: { name: "b", value: 2 },
c: { key: 1, status: true }
};
您还可以使用类型代替接口来实现相同的目的:
type MyObject = {
name: string,
value: number
};
type MyUnsafeObject = { [key: string]: any } & Partial<MyObject>;
另请参见:部分-https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt泛型-https://www.typescriptlang.org/docs/handbook/generics.html