打字稿动态特性和方法 [英] Typescript dynamic properties and methods

查看:64
本文介绍了打字稿动态特性和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解有关打字稿的更多信息.

I'm trying to learn more about typescript.

在javascript中,您可以编写一个函数,该函数返回具有动态添加的属性和方法的对象.

in javascript you can write a function that returns an object with properties and methods added dynamically.

例如(只是一个例子):

For example (just an example):

function fn(val) {
    var ret = {};

    if (val == 1) {
        ret.prop1 = "stackoverflow";
        ret.fn1 = function () {
            alert("hello stackoverflow");
        }
    }

    if (val == 2) {
        ret.fn2 = function () {
            alert("val=2");
        }
    }

    return ret;

}

window.onload = function(){

window.onload = function () {

    alert(fn(1).prop1); //alert "stackoverflow"
    fn(1).fn1(); //alert "hello stackoverflow"

    fn(2).fn2(); //alert "val=2"

}

在Visual Studio中,智能感知可以识别函数的返回值,并允许您使用参数和函数.

In the visual studio the intellisense recognize the return value of the function and allows you to use parameters and functions.

在第一张图片中有"prop1"和"fn1()",而不是"fn2()"

In the first image there are "prop1" and "fn1 ()" and not "fn2 ()"

在第二个图像中有"fn2()",而不是"prop1"和"fn1()".

In the second image there is "fn2 ()" and not "prop1" and "fn1 ()".

您可以用打字稿做类似的事情吗?怎么样?

you can do something similar with typescript? How?

想法是要有一个或多个函数,这些对象将返回具有属性和方法的对象,这些对象的属性和方法根据传递给该函数的参数而动态添加,并且可以从visual studio intellisense中看到.

The idea is to have one or more functions that return objects with properties and methods added dynamically based on the parameters passed to the function and visible from the visual studio intellisense.

谢谢

路卡

推荐答案

TypeScript接口可以具有可选成员.例如:

TypeScript interfaces can have optional members. e.g. :

interface Foo{
    prop1?:string;
    fn1?:Function;
    fn2?:Function;
}
function fn(val):Foo {
    var ret:Foo = {};

    if (val == 1) {
        ret.prop1 = "stackoverflow";
        ret.fn1 = function () {
            alert("hello stackoverflow");
        }
    }

    if (val == 2) {
        ret.fn2 = function () {
            alert("val=2");
        }
    }

    return ret;
}

您不需要创建显式接口.您可以内联:

You don't need to create an explicit interface. You can do it inline:

function fn(val) {
    var ret:{
        prop1?:string;
        fn1?:Function;
        fn2?:Function;
    }= {};

    if (val == 1) {
        ret.prop1 = "stackoverflow";
        ret.fn1 = function () {
            alert("hello stackoverflow");
        }
    }

    if (val == 2) {
        ret.fn2 = function () {
            alert("val=2");
        }
    }

    return ret;
}

这篇关于打字稿动态特性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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