gpt4 book ai didi

javascript - 如何使用 typescript 定义一个对象以具有不同的字段?

转载 作者:行者123 更新时间:2023-11-30 18:15:38 25 4
gpt4 key购买 nike

我有以下功能:

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

在另一个文件中我使用这个函数是这样的:

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

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

最佳答案

如果将 params 定义为接口(interface),则可以在函数括号后使用冒号将其声明为 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 显式声明为新的 IParams,但即使您不这样做,类型推断也会为您设置智能感知't,只要您分配给 params 对象的属性满足 IParams 接口(interface)中指定的契约(Contract)。

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

language specification非常详细地涵盖了所有这些,或者这里有一个简短的介绍:http://www.codeproject.com/Articles/469280/An-introduction-to-Type-Script或此处类似的 SO 问题:How to declare Return Types for Functions in TypeScript

关于javascript - 如何使用 typescript 定义一个对象以具有不同的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13330667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com