如何在Typescript + angular中检查空类对象的属性类型?

时间:2018-09-16 01:06:46

标签: typescript

Class Test{
  constructor(
     public a: number,
     public b: string
   ) {}
}
let t = new Test();

如何以编程方式检查t.a或t.b的类型?

1 个答案:

答案 0 :(得分:0)

TypeScript应该在编译时检查错误类型。但是,如果我们从外部获取数据-TypeScript无法帮助,我们希望进行运行时类型检查-io-ts

io-ts例如:

const Person = t.type({
  name: t.string,
  age: t.number
})

// runtime check
const result = Person.decode({ name: 'Giulio' })

console.log(PathReporter.report(result))
// => ['Invalid value undefined supplied to : { name: string, age: number }/age: number']

ThrowReporter.report(result)
// => throws 'Invalid value undefined supplied to : { name: string, age: number }/age: number'

interface IPerson extends t.TypeOf<typeof Person> {}

function getName(person: IPerson): string{
  return person.name;
}

// compile time check
getName({ name: 'Giulio' });