2017-12-20 3 views
0

저는 일반적으로 TypeScript와 OOP를 처음 사용합니다. 숙제로 간단한 디지털 시계를 만들어야합니다. 나는 수업을 사용해야한다. JS에서 만드는 것이 더 쉬웠으므로 잘 했으므로 제대로 작동합니다. 이제 TypeScript로 "되돌리기"위해 노력하고 있습니다. 또한 시간대를 변경하는 기능을 추가해야합니다.TypeScript에서 시계를 만드는 방법은 무엇입니까?

도와주세요!

내 작업 JS 버전은 다음과 같습니다

var clock = document.getElementById('clock'); 

function Clock() { 
    var time = new Date(); 
    var hours = time.getHours().toString(); 
    var minutes = time.getMinutes().toString(); 
    var seconds = time.getSeconds().toString(); 

    if (hours.length < 2) { 
    hours = '0' + hours; 
    } 

    if (minutes.length < 2) { 
    minutes = '0' + minutes; 
    } 

    if (seconds.length < 2) { 
    seconds = '0' + seconds; 
    } 

    var clockStr = hours + ' : ' + minutes + ' : ' + seconds; 

    clock.textContent = clockStr; 

} 

Clock(); 
setInterval(Clock, 1000); 

타이프 라이터 나의 작동하지 않는 코드는 다음과 같습니다

class Clock { 

    hours:number; 
    minutes:number; 
    seconds:number; 

    constructor(hours:number, minutes:number, seconds:number) { 

     this.hours = hours; 
     this.minutes = minutes; 
     this.seconds = seconds; 

    } 

    print() { 

     if (hours.length < 2) { 
      hours = '0' + hours; 
     } 

     if (minutes.length < 2) { 
      minutes = '0' + minutes; 
     } 

     if (seconds.length < 2) { 
      seconds = '0' + seconds; 
     } 

     var clockStr = hours + ' : ' + minutes + ' : ' + seconds; 

    } 

} 

function timeGenerate() { 

    let time = new Date(); 
    let hours = time.getHours(); 
    let minutes = time.getMinutes(); 
    let seconds = time.getSeconds(); 

} 

function clockRun() { 

    timeGenerate(); 
    let newClock = new Clock(hours, minutes, seconds); 
    newClock.print(); 

} 


clockRun(); 
setInterval(clockRun, 1000); 

document.getElementById('tsClock').innerHTML = newClock; 

내 HTML : 우리가 갈 직전에

<!DOCTYPE html> 
<html lang=""> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Typescript Clock</title> 

    <style> 
     body { 
     background-color: royalblue;  
     font-family: 'Lato'; 
     margin-top: 300px; 
     text-align: center; 
     color: ivory; 
     } 

     #clock { 
     font-weight: 300; 
     font-size: 100px; 
     } 
    </style> 


</head> 

<body> 

    <h1 id="tsClock"></h1> 
    <script src="app.js"></script> 

</body> 
</html> 
+2

타이프 모든 유효한 JS가 유효한 수단 스크립트의 수퍼,가요 TS. 처음에는 인수가 모두 'new Clock (시, 분, 초)'로 정의되어 있지 않습니다. – Phix

+0

나이가 아닌 일부 타이피 스크립트 마술 : https://gottz.de/uhr.htm https://gottz.de /binuhr.htm https://gottz.de/analoguhr.htm – GottZ

+0

@GotZ 멋지다! 코드를 공유 할 수 있습니까? –

답변

2

유효한 모든 자바 스크립트가 유효 타이프 라이터하지만, 다른 방법은 주위에있다.

TypeScript에는 범위 지정 문제가 있습니다.

다음 함수에서이 함수의 범위 내에 만있는 4 개의 변수를 선언하고 있습니다. undefined를 반환합니다.

function timeGenerate() { 
    let time = new Date(); 
    let hours = time.getHours(); 
    let minutes = time.getMinutes(); 
    let seconds = time.getSeconds(); 
} 

는 여기에서 정의되지 않은 변수와 함께 새로운 시계를 만들어, 아무것도하지 않는 timeGenerate 함수를 호출하고, print()를 호출하고 있습니다. 여기

function clockRun() { 
    timeGenerate(); 
    let newClock = new Clock(hours, minutes, seconds); 
    newClock.print(); 
} 


clockRun(); 
setInterval(clockRun, 1000); 

는 작동 최소한 예 (간단하게!)

class Clock { 
 
    // Declare a class variable of type "Element" called el 
 
    el: Element; 
 

 
    /** 
 
    * Called when "new" is invoked, you'll pass your target element here. 
 
    * @param element Target element to update 
 
    */ 
 
    constructor(element) { 
 
     this.el = element; 
 

 
     // Immediately kick off a setInterval to this objects "run" method, 
 
     // every 1000ms like you had before. 
 
     setInterval(() => this.run(), 1000) 
 
    } 
 
    
 
    /** 
 
    * This *could* be in the constructor, but for seperation of duties we'll 
 
    * make it a method. This method is invoked every ~1000ms (JavaScript timers 
 
    * aren't perfect). 
 
    */ 
 
    run() { 
 
     var time = new Date(); 
 
     // Don't need to call toString, but it's fine here. When you start 
 
     // concatenating numbers onto strings they get converted anyway. 
 
     var hours = time.getHours().toString(); 
 
     var minutes = time.getMinutes().toString(); 
 
     var seconds = time.getSeconds().toString(); 
 
     
 
     // Your previous logic. 
 
     if (hours.length < 2) { 
 
     hours = '0' + hours; 
 
     } 
 
    
 
     if (minutes.length < 2) { 
 
     minutes = '0' + minutes; 
 
     } 
 
    
 
     if (seconds.length < 2) { 
 
     seconds = '0' + seconds; 
 
     } 
 
     var clockStr = hours + ' : ' + minutes + ' : ' + seconds; 
 
     
 
     // Update this class' "el" variable as before. 
 
     this.el.textContent = clockStr; 
 
    } 
 
    } 
 

 
    // Create a new instance of Clock, passing in your target DOM element. 
 
    const clock = new Clock(document.getElementById('clock'))

Codepen

+0

컴파일 중에 오류가 발생합니다 : "app3.ts (24,11) : 오류 TS2339 : 'textContent'속성이 'Clock'유형에 없습니다." 이 줄은 어떨까요 : "document.getElementById ('tsClock'). innerHTML = newClock;" 나는 그것이 어딘가 배치되어야한다고 생각하지 않습니까? 이 코드가 작동하지 않습니다, 난 그냥 배경으로 일반 사이트가 있습니다. –

+0

미안, 나는 집에 돌아 서서 서둘러야했다. 그리고 그것은 약간 불완전했다. 위의 코드를 시도해보십시오. – Phix

+0

이제 작동합니다! 이상한 것은이 시계가 unstyled다는 것입니다. 이 코드에 몇 가지 의견을 보내 주시겠습니까? 나는 그것을 이해해야한다 100 % –

1

귀하의 코드를 통해. 브라우저에서는 타이프 스크립트를 읽을 수 없다는 것을 알아야합니다. 따라서 JavaScript (ES 5)로 컴파일해야합니다. 따라서 index.html은 typescript 파일이 아닌 컴파일 된 JavaScript를 가져와야합니다.

이제 코드에 가자 :

class Clock { 

    hours:number; 
    minutes:number; 
    seconds:number; 

    constructor(hours:number, minutes:number, seconds:number) { 

     this.hours = hours; 
     this.minutes = minutes; 
     this.seconds = seconds; 

     this.clockRun(); 
     setInterval(this.clockRun, 1000); 

     document.getElementById('tsClock').innerHTML = newClock; 

    } 

    print() { 

     if (hours.length < 2) { 
      hours = '0' + hours; 
     } 

     if (minutes.length < 2) { 
      minutes = '0' + minutes; 
     } 

     if (seconds.length < 2) { 
      seconds = '0' + seconds; 
     } 

     var clockStr = hours + ' : ' + minutes + ' : ' + seconds; 

    } 

} 

timeGenerate() { 

    let time = new Date(); 
    let hours = time.getHours(); 
    let minutes = time.getMinutes(); 
    let seconds = time.getSeconds(); 

} 

clockRun() { 

    this.timeGenerate(); 
    let newClock = new Clock(hours, minutes, seconds); 
    this.print(); 

} 
+1

예, 내 index.html이 app.js를 가져오고 .ts를 .js에 알리도록 컴파일하는 방법을 알고 있습니다. –

관련 문제