#独家
typescript的interface多属性间如何约束?

2023-04-15 0 2,022

rt,预期当品类species为Cat时,animalsType只能为Cat对应的string。
但实际上animalsType成为了联合类型

代码如下:

type SpeciesType = "Cat" | "Dog"
interface AnimalsType {
    Cat: String
    Dog: Number
}
interface Animals<T extends SpeciesType> {
    species: T
    animalsType: AnimalsType[T]
}


const animalList: Animals<SpeciesType>[] = [
    // ok
    {
        species: "Cat",
        animalsType: "1",
    },
    // ok
    {
        species: "Dog",
        animalsType: 1,
    },
    // expect:error!
    // 此处预期结果应该报错,希望从联合类型中取出Cat对应的为string
    {
        species: "Cat",
        animalsType: 1,
    },
]

补充说明:
我已经了解到可以将Animals声明为联合类型来解决,但这个方案不适用于我的具体问题
示例如下:

type SpeciesType = "Cat" | "Dog"
interface AnimalsType {
    Cat: String
    Dog: Number
}
type Animals = {
    species: "Cat"
    animalsType: String
} | {
    species: "Dog"
    animalsType: Number
}

// 预期为:

const animalList: Animals[] = [
    // ok
    {
        species: "Cat",
        animalsType: "1",
    },
    // ok
    {
        species: "Dog",
        animalsType: 1,
    },
    // expect:error!
    // 此处预期结果应该报错,希望从联合类型中取出Cat对应的为string
    {
        species: "Cat",
        animalsType: 1,
    },
]

感觉这个类型可以转化为类型推断问题
将T具体推断为Cat/Dog,从而获取到对应的animalsType

type Animals = {
  [K in keyof AnimalsType]: {
    species: K;
    animalsType: AnimalsType[K]
  }
}[keyof AnimalsType]
const animalList: Animals[] = [
    // ok
    {
        species: "Cat",
        animalsType: "1",
    },
    // ok
    {
        species: "Dog",
        animalsType: 1,
    },
    // error!
    {
        species: "Cat",
        animalsType: 1,
    },
]
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 typescript的interface多属性间如何约束? https://www.jkxiazai.com/1532.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务