0
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 的正确方法,我如何在界面中描述我的方法(我计划添加更多)?

4

2 回答 2

1

这一切都取决于你需要你的界面做什么。通常是用接口表示对象的形状,因此显式键入所有方法,然后让对象“实现”它:

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()在于它返回 type Array<string>,但string无法索引没有索引签名的对象。请参阅此处了解基本原理。给定类型对象的键的类型Tkeyof T,因此(Object.keys(obj) as (keyof Keys)[])我告诉 TypeScript 将键数组“解释”为类型Array<keyof Keys>,以便它可以索引对象,例如obj[key]. 主要问题是,在某些情况下,对象可以具有其他可枚举属性,而不是其类型中表示的属性,因此在实践中,给出的每个键Object.keys()都是 type 是不正确的keyof T;但是,如果您确定该对象没有其他属性,例如在示例中obj是从对象字面量创建的,则断言是安全的,但您需要明确表达。

于 2019-10-11T19:29:30.603 回答
0
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])
})
于 2019-10-11T19:03:25.667 回答