Typescript 里能做到下方代码中对参数保护的需求吗,防止字段输入错位?

type AccountID = number
type Money = number

interface Request {
    accountID: AccountID,
    money: Money,
}

declare let r: Request

function testString(i: number) {}
function testAccountID(id: AccountID) {}
function testMoney(money: Money) {}

testString(r.accountID)
testString(r.money)

testAccountID(r.accountID)
testAccountID(r.money) // 希望报错

testMoney(r.accountID) // 希望报错
testMoney(r.money)
阅读 1.4k
2 个回答

你目前定义的两个类型:AccountID Money 无法区分,都是 number 类型,确实需要区分的话,建议封装一下:

class AccountID {
  value: number
}

class Money {
  value: number
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进