简体   繁体   中英

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

I have simple js component

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

it has typescript definition file

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

Very simple typescript/react project is consuming this component:

./demo/index.tsx:

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

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

Expected result : typescript error indicating that value of 't' is expected to be number but received string instead.

Actual result : no errors or warnings from typescript.

Here is small project that reproduces this issue, I tried to make it as minimal as possible, just do:

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

I checked the official docs but it doesn't help (they mention 12 instead numeric type in the examples which confuses), Also provided there playground doesn't seem to be useful for this use case.

I believe that when you provide a d.ts it uses that as gospel, and flat out ignores any code in your code files.

So in your case t is a number . So in react <div>{t}</div> is totally valid, react will coerce that to display the number so there isn't any type errors expected here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM