tuia-fed / weekly-question

应对疫情,网上交流
2 stars 0 forks source link

【Typescript】第一题 #112

Open zhouchao941105 opened 2 years ago

zhouchao941105 commented 2 years ago

a,b,c三个属性的值都是number类型。假设这样一个场景,一个对象obj一定有a这个属性,如果有b的话,c也必定存在,即obj={a:1}或者a={a:1,b:1,c:1};要求obj不是这两种情况下,给出错误提示

LiuSandy commented 2 years ago
type IBC = {
  b:number
  c:number
}

type Obj<T=any> = {
  [k in keyof T]: T[k]
} & {
  a: number
}

const a:Obj= {
  a:12,
}
const abc<IBC> = {
  a:12,
  b:1,
  c:2
}
Highnesslin commented 2 years ago

// 全部字段
type IAllField = {
  a: number
  b: number
  c: number
}
// 只有a这个字段
type IAField = {
  a: number
}

// 动态校验
type IValidateFiled<T> = T extends {
  a: number
}
  ? T extends {
      b: number
    }
    ? T extends {
        c: number
      }
      ? T
      : IAllField
    : T
  : IAllField | IAField

declare function validate<T>(x: IValidateFiled<T>): T

// 测试
const testObj = validate({
  a: 1,
  b: 1,
})
ding2650 commented 2 years ago

interface IAllField {
  a: number
  b: number
  c: number
}
// 只有a这个字段
interface IAField {
  a: number
}

interface IABField {
  a: number
  b: number
}
interface IACField {
  a: number
  c: number
}
// 动态校验
type IValidate<T> = T extends IABField | IACField | IAllField ? IAllField : IAField

declare function f<T>(x: IValidate<T>): T

// 测试
const testObj = f({
  a: 1,
  b: 2
})
zhouchao941105 commented 2 years ago

https://codesandbox.io/s/sleepy-brook-tip7j?file=/src/index.ts