Need help to write following javascript code in typescript, it is a simple class with two public functions:
var Myclass = (function () { var teststr = ['ein test','noch ein test']; function Myclass (){ this.test(); } function getStr (id) { return teststr[id]; } Myclass.prototype.test = function () { console.log(getStr(0)) this.test1(); } Myclass.prototype.test1 = function () { console.log(getStr(1)) } return Myclass; })(); var instMyClass = new Myclass();
- var instMyClass call the constructor , than the constructor call public function test.
- function test give out the first element of private array teststr and call public function test1
- function test1 give out the second elemement of private array teststr
i try this solution, bur typescript compilier shows errors
class Myclass { private teststr:Array<string> = ['ein test','noch ein test']; constructor() { this.test(); } function getStr() { return teststr[id]; } test() { console.log(getStr(0)); this.test1(); } test1(str:string) { console.log(getStr(1)); } } let instMyclass = new Myclass();
if i try a private function with a form.submit, than the function is undefined:
class Ticket { private form: HTMLFormElement; constructor() { this.form = document.forms[0]! this.form.onsubmit = this.submit; } private setUser (user: TicketUser):void { console.log('ticket setUser',user); } public submit ():any { console.log('ticket submit'); this.setUser({name:'stefan',age:100}); return false; } }
Advertisement
Answer
Can you try with the typescript code below . Updated my answer
ts file
class Ticket { private form: HTMLFormElement; constructor(elem: HTMLFormElement) { this.form = elem; //this.form.onsubmit = this.submit(); } private setUser(user: TicketUser): void { console.log('ticket setUser', user); } public submit(): any { console.log('ticket submit'); this.setUser({ name: 'stefan', age: 100 }); return false; } } class TicketUser { name: string; age: number; } window.onload = () => { var btn = document.getElementById("btn"); btn.onclick = function () { var form = document.forms[0]; var ticket = new Ticket(form); form.onsubmit = ticket.submit(); } };
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>TypeScript HTML App</title> <link rel="stylesheet" href="app.css" type="text/css" /> </head> <body> <h1>TypeScript test</h1> <form id="myform" action="#"></form> <br /> <button id="btn">click me</button> <script src="test.js"></script> </body> </html>