javascript - 如何在 Typescript 中对重载函数进行命名导出?
问题描述
pickCard.ts
这是来自的示例:
https://www.typescriptlang.org/docs/handbook/functions.html#overloads
function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x: any): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
export pickCard; // DOES NOT WORK
我不能使用这样的函数表达式:export const pickCard = () => {};
因为重载不适用于函数表达式。
问题
如何对pickCard
函数进行命名导出。注意:名字应该是pickCard
解决方案
这对我有用:
export function pickCard(x: { suit: string; card: number }[]): number;
export function pickCard(x: number): { suit: string; card: number };
export function pickCard(x: any): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
在其他文件中使用:
import { pickCard } from ".";
pickCard([{ suit: 'test', card: 10 }]);
pickCard(21);
推荐阅读
- python - Python ThreadPoolExecutor 提交语法
- webrtc - 如何让我的 WebRTC 正常工作
- javascript - 删除数组中的元素,这些元素是重复的,并且顺序跟随
- python - Python没有正确读取文件
- flutter - 返回页面后恢复 AnimationController 状态
- google-cloud-platform - 调用 Google 数据流 RestApi 时出现间歇性 401 未经身份验证的问题
- r - 如何获取 xgb.DMatrix 的索引以添加 feval 函数的信息?
- jquery - 如何从 TD 内部获取 href 值
- java - OpenWeatherMap 将 arraylist 转换为 Map
- android - Flutter,RawKeyboardListener 在 Enter 按键后获取文本