动态TypeScript键入

时间:2016-12-01 15:38:37

标签: javascript typescript typescript-typings

有没有办法在TypeScript类中拥有动态对象属性,并为TypeScript添加动态类型?

我见过类似的问题,但没有一个像这样的完整例子 -

import java.awt.*;
import java.io.*;

//Banner class
class Banner extends Frame implements Runnable 
{
    boolean stop=false;
    String str="Sreedhar Practice seassion";
    //constructor
    public Banner()
    {
        setLayout(null);
        setBackground(Color.cyan);
        setForeground(Color.blue);
    }//end of constructor

    //image paint settings methosd
    public void paint(Graphics g)
    {
        Font f=new Font("Courier",Font.BOLD,40);
        g.setFont(f);
for (int i=0;i<=str.length() ;i++ )
        {
            char ch=str.charAt(i);
            String c=String.valueOf(ch);
            g.drawString("\t"+c,10,100);
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException ie)
            {
            }
            //char ch=str.carAt(0);
            //str=str.substring(1,str.length());
            //str=str+ch;
            if (stop)
            {
                return;
            }
        }

    }//image paint settings methosd end

    //start of run method
    public void run()
    {
            if (stop)
            {
                return;
            }
        }
    }//end of run method

    //main method starting
    public static void main(String[] args)throws IOException 
    {
        Banner b=new Banner();
        b.setSize(400,400);
        b.setTitle("Sreedhar Banner");
        b.setVisible(true);
        Thread t=new Thread(b);
        t.start();
        System.in.read();
        b.stop=true;
    }//end of main method
}//end of class Banner

2 个答案:

答案 0 :(得分:3)

您可以使用工厂功能和intersection

function factory<A extends IHasObjectName, B extends IHasObjectName, C>(a: A, b: B): example<A, B> & C {
    return new example<Cat, Dog>(a, b) as C;
}
var test = factory<Cat, Dog, { Dog(): Dog, Cat(): Cat }>(cat, dog);

var d = test.Dog(); // no error
var c = test.Cat(); // no error

code in playground

修改

你不能反映&#34;类型因为它们不存在于运行时,但您可以使用传入实例的constructor.name,因此您可以简单地执行此操作:

class example<A, B> {
    constructor(a: A, b: B) {
        this[a.constructor.name] = function() { return a; };
        this[b.constructor.name] = function() { return b; }
    }
}

class Cat {}

class Dog {}

var cat = new Cat();
var dog = new Dog();


function factory<A, B, C>(a: A, b: B): example<A, B> & C {
    return new example<Cat, Dog>(a, b) as C;
}
var test = factory<Cat, Dog, { Dog(): Dog, Cat(): Cat }>(cat, dog);

var d = test.Dog();
var c = test.Cat();

code in playground

答案 1 :(得分:0)

如果你想要&#34; JavaScript行为&#34;你需要将它转换为any对象类型。在TypeScript中。

有两种语法类型,它们是等价的:

const d = (<any>test).Dog();
const c = (<any>test).Cat();

const testAny = test as any;
const d = testAny.Dog();
const c = testAny.Cat();

最后一个是为了tsx文件中的支持而创建的,这些文件不起作用,现在是推荐的方式。

除了使用索引器之外,几乎没有其他方法可以做到这一点,因为属性是动态的而不是键入的。

BTW我鼓励使用constlet代替var

相关问题