[英]How can I define an object to have different fields using typescript?
I have the following function:我有以下功能:
function getAdminParams(entity) {
params = {};
params = {
pk: "0006000",
param: "?pk=0006000",
table: "Content",
success: true
};
return params;
}
In another file I use this function like this:在另一个文件中,我像这样使用这个函数:
params = getAdminParams(entity);
if (params.success) {
Is there a way that I could use intellisense so that the params object shows as having a "success" parameter?有没有办法可以使用智能感知,以便 params 对象显示为具有“成功”参数? I saw that Typescript has classes and interfaces but I am not sure how or if I can use these as a return type.
我看到 Typescript 有类和接口,但我不确定如何或是否可以将它们用作返回类型。
If you define params as an interface, then you can use a colon after the function parentheses to declare it as the return type of getAdminParams()
.如果将 params 定义为接口,则可以在函数括号后使用冒号将其声明为
getAdminParams()
的返回类型。 Like this:像这样:
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).
Within getAdminParams
you could explicitly declare params
as a new IParams
, but type inference will set up the intellisense for you even if you don't, as long as the properties you assign to the params
object fulfill the contract specified in the IParams
interface.在
getAdminParams
您可以将params
显式声明为新的IParams
,但类型推断将为您设置智能感知,即使您不这样做,只要您分配给params
对象的属性满足IParams
接口中指定的IParams
。
Of course your return type could be a class, or a string, or any other type, and you would declare that using the function f(): returnType
syntax in just the same way.当然,您的返回类型可以是一个类、一个字符串或任何其他类型,您可以以同样的方式使用
function f(): returnType
语法声明它。
The language specification covers all of this in great detail, or there is a shorter introduction here: http://www.codeproject.com/Articles/469280/An-introduction-to-Type-Script or a similar SO question here: How to declare Return Types for Functions in TypeScript语言规范非常详细地涵盖了所有这些,或者这里有一个简短的介绍: http : //www.codeproject.com/Articles/469280/An-introduction-to-Type-Script或类似的 SO 问题在这里: How在 TypeScript 中声明函数的返回类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.