You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中应定义入参相同的函数还是转为带实例方法的类?

适用TS这类场景的3种主流实践,你可以根据业务复杂度选:

1. 接口+同名命名空间(最推荐,适配90%业务场景)

这是TS生态对接API时最常用的模式,既不需要做JSON到类实例的转换,也不会出现零散的全局函数:

// 先定义纯数据接口,和API返回的字段完全对齐,不需要任何方法
interface Hand {
  rank: number
  suit: string
}

// 同名命名空间,把所有和Hand相关的工具函数都收敛在这里
namespace Hand {
  export function getHandName(hand: Hand) {
    return `${hand.rank} of ${hand.suit}`
  }

  export function getHandScore(hand: Hand) {
    return hand.rank * 10 // 你的计算逻辑
  }

  export function isBetterThan(target: Hand, comparison: Hand) {
    return getHandScore(target) > getHandScore(comparison)
  }
}

使用时直接拿API返回的符合Hand结构的JSON调用即可,不需要任何转换:

const apiHand = await fetch('/api/hand').then(res => res.json())
console.log(Hand.getHandName(apiHand))
console.log(Hand.isBetterThan(apiHand, otherHand))

2. 闭包工厂函数(适合单数据对象多方法调用场景)

如果你不想每次调用方法都传一遍hand参数,用工厂函数比新建Service类要自然得多:

function createHandHelper(hand: Hand) {
  // 还可以在这里做计算结果缓存,避免重复计算
  const score = Hand.getHandScore(hand)

  return {
    getHandName: () => `${hand.rank} of ${hand.suit}`,
    getHandScore: () => score,
    isBetterThan: (other: Hand) => score > Hand.getHandScore(other)
  }
}

使用方式:

const handHelper = createHandHelper(apiHand)
console.log(handHelper.getHandName())
console.log(handHelper.isBetterThan(otherHand))

3. 带静态转换方法的Class(适合重度OOP习惯、类有内部状态的场景)

如果你还是习惯用类的实例方法,只要加一个统一的JSON转实例的静态方法即可,避免每次手动强转:

class Hand {
  rank: number
  suit: string

  constructor(rank: number, suit: string) {
    this.rank = rank
    this.suit = suit
  }

  // 统一转换逻辑,还可以加字段校验
  static fromJSON(json: Pick<Hand, 'rank' | 'suit'>) {
    if (typeof json.rank !== 'number' || typeof json.suit !== 'string') {
      throw new Error('Invalid Hand data')
    }
    return new Hand(json.rank, json.suit)
  }

  getHandName() {
    return `${this.rank} of ${this.suit}`
  }

  getHandScore() {
    return this.rank * 10
  }

  isBetterThan(other: Hand) {
    return this.getHandScore() > other.getHandScore()
  }
}

使用方式:

const hand = Hand.fromJSON(apiHand)
console.log(hand.getHandName())

内容的提问来源于stack exchange,提问作者Nerdsie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 02:15:03