簡體   English   中英

使用 typescript 定義文件 (.d.ts) 鍵入 javascript 代碼不會警告原始類型錯誤

[英]using typescript definition file (.d.ts) for typing javascript code doesn't warn about primitive type errors

我有簡單的 js 組件

./component/index.js: export const t = 'string value';

它有 typescript 定義文件

./component/index.d.ts: export const t: number;

非常簡單的 typescript/react 項目正在使用這個組件:

./demo/index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import { t } from '../component';

ReactDOM.render(<>{ t }</>, document.getElementById('app'));

預期結果:typescript 錯誤,表明 't' 的值應為數字但接收到的字符串。

實際結果:typescript 沒有錯誤或警告。

是重現此問題的小項目,我試圖使其盡可能小,只需執行以下操作:

  • git clone git@github.com:omatviiv/ts-definition-file-test.git
  • npm i
  • npm run dev

我檢查了官方文檔,但沒有幫助(他們在示例中提到了12而不是數字類型,這令人困惑),還提供了游樂場似乎對這個用例沒有用處。

我相信,當您提供d.ts時,它會將其用作福音,並且會完全忽略代碼文件中的任何代碼。

所以在你的情況下t是一個number 所以在 react <div>{t}</div>是完全有效的,react 會強制它顯示數字,所以這里不會出現任何類型錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM