将索引签名与方法结合使用 - 打字稿 3.5


interface Keys {
[key: string]: any
}
const obj: Keys = {
trimDescription(text: string, length: number): string {
return text.length > length ? text.substring(0, length - 3) + '...' : text
}
}
Object.keys(obj).forEach(key => {
console.log(obj[key])
})

我在界面中使用any,但这不是使用 TS 的正确方法,我如何在界面中描述我的方法(我计划再添加一些(?

这完全取决于您需要接口做什么。通常的做法是用接口表示对象的形状,因此显式键入所有方法,然后让对象"实现"它:

interface Keys {
trimDescription(text: string, length: number): string;
makeUppercase(description: string, active: boolean): string;
}
const obj: Keys = {
trimDescription(text, length) {
return text.length > length ? text.substring(0, length - 3) + '...' : text;
},
makeUppercase(description, active) {
// ...
},
};
(Object.keys(obj) as (keyof Keys)[]).forEach(key => {
console.log(obj[key]);
});

我想索引签名不是您想要的。不需要索引签名,除非你需要某种类型的属性"包",那么你的所有属性都必须符合该签名。

您还可以从您创建的对象推断类型:

const obj = {
trimDescription(text: string, length: number): string {
return text.length > length ? text.substring(0, length - 3) + '...' : text;
},
makeUppercase(description: string, active: boolean): string {
// ...
},
};
// Inferred from the implict shape of the object
type Keys = typeof obj;
(Object.keys(obj) as (keyof Keys)[]).forEach(key => {
console.log(obj[key]);
});

操场

也许你应该考虑使用一个类。

Object.keys()的问题在于它返回类型Array<string>,但string不能在没有索引签名的情况下索引对象。有关基本原理,请参阅此处。T型给定对象的键类型是keyof T,因此(Object.keys(obj) as (keyof Keys)[])我告诉 TypeScript 将键数组"解释"为类型Array<keyof Keys>,以便它可以索引对象,如obj[key]。主要问题是,在某些情况下,对象可以具有与其类型中表示的属性以外的其他可枚举属性,因此在实践中,Object.keys()给出的每个键都属于keyof T类型;但是,如果您确定该对象没有其他属性,例如在从对象文本创建obj的示例中,则断言是安全的,但您需要显式表达。

interface Keys {
[key: string]: (text: string, length: number) => string;
}
const obj: Keys = {
trimDescription(text: string, length: number): string {
return text.length > length ? text.substring(0, length - 3) + '...' : text
}
}
Object.keys(obj).forEach(key => {
console.log(obj[key])
})

最新更新