Angularのための、TypeScript入門 その4
参考サイト
https://www.codingforentrepreneurs.com/projects/getting-started-typescript/
Typescript - Classes - Part 3
main.tsをsrc/内に移動させる。
archiveというフォルダを作成して、不要になったmain.tsなどを移動させておく。(なぜ削除しないかはいまのところ不明)
webpack.config.js
に、新しいmain.tsのpathを設定する。
var path = require('path'); module.exports = { entry: './src/main.ts', resolve: { extensions: ['.webpack.js', '.web.js', '.ts', '.js'] }, module: { loaders: [ { test: /\.ts$/, loader: 'ts-loader' } ] }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } }
- webpack –watch でerrorが発生!
ERROR in /path/tsconfig.json error TS18003: No inputs were found in config file 'tsconfig.json'. Specified 'include' paths were '["*"]' and 'exclude' paths were '["node_modules","**/*.spec.ts"]'. ERROR in ./src/main.ts Module build failed: error while parsing tsconfig.json
- tsconfig.jsonを修正する。inclludeに、
"src/*",
を追記する。これで、error解消!
{ "compilerOptions": { "module": "commonjs", "outDir": "dist/", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true }, "include": [ "src/*", "*" ], "exclude": [ "node_modules", "**/*.spec.ts" ] }
- main.tsに、MustHaveCoffeeを継承して独自のメソッドを追記する。
import { MustHaveCoffee } from './coffee/getcoffee'; class ReallyCoffee extends MustHaveCoffee { constructor(){super()} // ここで、constructor の継承を行う f(input: boolean){ // ここはfunctionという名前で指定しなくてもいいのか?それは省略できるのか。 let a = 100 if (input) { let b = a + 100012 return b; } return a; } } let newCoffee = new ReallyCoffee() let count = newCoffee.f(true) console.log(count) let odlCoffee = new MustHaveCoffee()
- MustHaveCoffee classにsetCoffeeTypeを追記する。
export class MustHaveCoffee{ coffeeType: string; constructor(){ console.log("Make it bulletproof") } setCoffeeType(name:string){ this.coffeeType = name } }
- ReallyCoffee classで上書きなどのテストをしてみる。
import { MustHaveCoffee } from './coffee/getcoffee'; class ReallyCoffee extends MustHaveCoffee { coffeeType = 'tenshi'; constructor(){super()} // ここで、classの継承を行う f(input: boolean){ let a = 100 if (input) { let b = a + 100012 return b; } return a; } setCoffeeType(name:string){ // super.setCoffeeType(name) このように記述するとオーバーロードできる。 // super(ReallyCoffee, self).setCoffeeType(name) >python風 console.log("hello there " + "test " + this.coffeeType) } } let newCoffee = new ReallyCoffee(); newCoffee.f(true); newCoffee.setCoffeeType("bulletproof"); let odlCoffee = new MustHaveCoffee()
まとめ
- 実は継承の部分は、記述がpythonより楽かもしんないな。