NodeJS 有关typescript注解和节点包的基本问题

wnrlj8wa  于 2022-11-04  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我是typescript的新手,了解它的基础知识。但是当我在项目中使用包时,我对节点包、注解和描述这些类型的最佳实践有点困惑。
我的意思是,真的需要描述一个包的返回注解,或者在包使用的参数中指定数据类型吗?
让我们以mysql 2包为例。
`

const poolFunction = async (SQL: string): Promise < [RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]] > => {
    return await pool.query(SQL);
}

或表达...

const routeFunction = (req: Request, res: Response): void => {
}

`
当然,它是非常描述性的,但它是必要的吗?
只是试着理解,并希望在未来的打字稿!

e4eetjau

e4eetjau1#

是否真的需要描述一个包的返回注解,或者在它们的参数中指定数据类型,当它们已经用下载的@类型定义时,这些参数被包使用?
在你的例子中,是的,因为TypeScript不能知道routeFunction是否要和某个Express函数一起使用。通过隔离它,你必须键入参数,尽管返回类型可以推断出来。
如果您传送 expected function,TypeScript将会推断参数的型别,例如:

// no need to type app because TS already knows
// the return type of express()
const app = express();

// no need to type request or response because TS already knows
// that .get() expects a function of 2 parameters, a Request and a Response
app.get('', (request, response) => {});

// since routeFunction is declared outside an Express context,
// TS can't know that request: Request and response: Response,
// this function can be used anywhere not only for Express
function routeFunction(request, response) {} // error

相关问题