定义TypeScript变量类型函数或字符串 [英] Defining TypeScript variable type function or string

查看:69
本文介绍了定义TypeScript变量类型函数或字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个界面:

interface IParameters {
    form: number;
    field: string;
    ...
}

我希望 form 属性是数字或函数,而 field 是字符串或函数.

I want the formproperty to be number or function and field to be string or function.

我尝试这样的事情:

interface IParameters {
    form: number | Function;
    field: string | Function;
    ...
}

我需要这个,因为在我的代码中,我使用了这样的变量:

I need this because in my code i use this variables like this:

var form = (typeof _oParameters.form === "function" ? _oParameters.form() : _oParameters.form);
var field = (typeof _oParameters.field === "function" ? _oParameters.field() : _oParameters.field);

我不想在我的所有代码中将此变量从字符串/数字更改为默认函数,并避免将此变量设置为其他类型.

I don't want change this variable in all my code from string/number to default function and to prevent setting this variables to other types.

但是如果我尝试调用这两个变量之一,例如函数:

but if I try to call one of this two variable like function:

var param:IParameters;
param.form();
...

我收到此错误:

无法调用类型缺少调用签名的表达式.

Cannot invoke an expression whose type lacks a call signature.

但是 param.form = 12; 有效.

我发现的唯一解决方案是将 form field 声明为 any 类型.

The only solution that i have found is to declare form and field to any type.

是否是没有任何类型的情况下定义此变量的另一种方法?

Is other way to define this variable without any type?

推荐答案

也许您是使用呼叫签名而不是 Function 来定义联合类型的,就像这样...

Perhaps if you define your union type using a call signature rather than Function, like so...

interface IParameters {
    // form is of type function that returns number, or number literal.
    form: () => number | number;

    // field is of type function that returns a string, or string literal.
    field: () => string | string;
}

class Foo {
    constructor (param: IParameters) {
        var x = typeof param.form === "number" ? param.form : param.form();
        var y = typeof param.field === "string" ? param.field : param.field();
    }
}

在这里,我仍在使用 typeof 检查 form field ,但是TypeScript很高兴将其用作函数调用或一个值.

Here, I am still checking form and field using typeof, however TypeScript is happy for it to be either a function call, or a value.

这篇关于定义TypeScript变量类型函数或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆