# typesciprt seems fun ###### tags: `note`, `TODO` > 一篇三年前的筆記,一直沒有更新。整理筆記時看到就順手加兩筆,如果哪一天需要用到 TS 再回來補,總之先公開 > [name=AnJung 2025/03/17] ### type ```typescript= let num: number; function foo(a: number, b: string): string { return a + b; } ``` ```typescript= function bar(input: any): void { return; } ``` 什麼型態都不給它會生氣氣,你可以塞一個 `any` 給它,然後那個變數的行為基本上就會跟 js 一樣。 #### typing.d.ts `xxx.d.ts` 是用來定義一些非 ts 的東西要怎麼 import (基本上就是用 ts 定義一下那些東西也是一種 module,不然 ts 不給你隨便 import) ```typescript= declare module "*.vue" { import Vue from 'vue'; export default Vue; } declare module "*.json" { const value: any; export default value; } declare module "*.png" { const value: any; export = value; } ``` ### interface > 看官網似乎其實並沒有建議 interface 需要 I 開頭 > [name=AnJung 2022] > interface I 開頭是 $軟 `C#` 風格,很多其他語言都是沒有要求 Interface 要取 `I` 前綴 [name=AnJung 2025] ```typescript= interface IObjectConfig { scene: Phaser.Scene; x: number; y: number; textureKey: string; } interface IMyInterfaceForSomeClass { x: number; ... } class MySomeClass implement IMyInterfaceForSomeClass { } ``` ### class type 問題 當直接 import class 並打算把它作為一個 type 做參考時便會出錯 ```typescript= // file: Foo.ts class Foo { // bla bla bla } export default Foo; // export the class ``` ```typescript= // client import Foo from './Foo.ts' let foo: Foo; // Error: 'Foo' refer to a value, but is being a type here... ``` 因為 `import`, `export` 為 javascript dynamic 的東東,因此 client import 近來的東西會被視為 javascript 的 value,而不是 typescript 中的一種 type 最最簡單的解法為修改 client 為: ```typescript= // client import Foo from './Foo.ts' let foo: InstanceType<typeof Foo>; // kind a stupid but works ``` - [stackoverflow solution detail](https://stackoverflow.com/questions/62059408/reactjs-and-typescript-refers-to-a-value-but-is-being-used-as-a-type-here-ts)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up