1

我有以下功能:

function getAdminParams(entity) {
   params = {};
   params = {
                pk: "0006000",
                param: "?pk=0006000",
                table: "Content",
                success: true
            };
  return params;
}

在另一个文件中,我像这样使用这个函数:

params = getAdminParams(entity);
    if (params.success) {

有没有办法可以使用智能感知,以便 params 对象显示为具有“成功”参数?我看到 Typescript 有类和接口,但我不确定如何或是否可以将它们用作返回类型。

4

1 回答 1

2

如果将 params 定义为接口,则可以在函数括号后使用冒号将其声明为getAdminParams(). 像这样:

interface IParams {
    success: bool;
    pk: string;
    // etc...
}

function getAdminParams(entity): IParams {
    params = {
                pk: "0006000",
                success: true
                // etc...
            };
    return params; // If the properties assigned do not fulfill the IParams interface, this will be marked as an error.
}

params = getAdminParams(entity);
if (params. // Intellisense should offer success and pk and any other properties of IParams).

您可以在其中getAdminParams显式声明params为 new IParams,但即使您不这样做,类型推断也会为您设置智能感知,只要您分配给params对象的属性满足IParams接口中指定的合同即可。

当然,您的返回类型可以是类、字符串或任何其他类型,您可以使用function f(): returnType相同的语法声明它。

语言规范详细介绍了所有这些,或者这里有一个更简短的介绍:http: //www.codeproject.com/Articles/469280/An-introduction-to-Type-Script或类似的 SO 问题:How在 TypeScript 中声明函数的返回类型

于 2012-11-11T11:34:43.553 回答