记录一次TypeScript错误

Rinsann 2021年10月29日 783次浏览

记录一次TypeScript错误

[ERROR] 23:37:21 ⨯ Unable to compile TypeScript:
index.ts(11,9): error TS7034: Variable 'array' implicitly has type 'any[]' in some locations where its type cannot be determined.
index.ts(16,32): error TS7005: Variable 'array' implicitly has an 'any[]' type.

image20211029233731271.png

import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';

const server = http.createServer();


server.on('request', (request: IncomingMessage, response: ServerResponse) => {
  console.log(request.method);
  console.log(request.url);
  console.log(request.headers);
  //const array = []; // 原因是array没有指定类型
  const array:Buffer[] = []; // 指定类型后代码正确
  request.on('data', (chunk:Buffer) => {
    array.push(chunk);
  });
  request.on('end', () => {
    const body = Buffer.concat(array).toString();
    console.log('body');
    console.log(body);
    response.end('hi');
  });
});

server.listen(8888);

TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.

import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';
import * as fs from 'fs';
import * as p from 'path';
import * as url from 'url';

const server = http.createServer();
const publicDir = p.resolve(__dirname, 'public'); //public所在的绝对路径 __dirname表示当前目录
let cacheAge = 3600 * 24 * 365;

server.on('request', (request: IncomingMessage, response: ServerResponse) => {
  const {method, url: path, headers} = request;
  const {pathname, search} = url.parse(path!);
  // 或 解构的时候默认空字符串
  // const {pathname, search} = url.parse(path || '');
  if (method !== 'GET') {
    response.statusCode = 200;
    response.end('这是一个假响应');
    return;
  }

  // response.setHeader('Content-Type', 'text/html;charset=utf-8');
  // /index.html => index.html
  let filename = pathname!.substr(1);
  if (filename === '') {
    filename = 'index.html';
  }

  fs.readFile(p.resolve(publicDir, filename), (error, data) => {
    if (error) {
      console.log(error);
      if (error.errno === -4058) {
        response.statusCode = 404;
        fs.readFile(p.resolve(publicDir, '404.html'), (error, data) => {
          response.end(data);
        });
      } else if (error.errno === -4068) {
        response.statusCode = 403;
        response.end('无权限查看此目录');
      } else {
        response.statusCode = 500;
        response.end('服务器繁忙,请稍等');
      }

    } else {
      //返回文件内容
      response.setHeader('Cache-Control', `public, max-age=${cacheAge}`);
      response.end(data);
    }
  });
});

server.listen(8888);