Gul*_*llu 5 javascript typescript tslint
最近从 C# 迁移到 TypeScript。下面的代码工作正常并且没有错误。然而我怀疑我还没有理解一些 TS 基础知识,因为我们只是定义接口并像对象/类一样使用它们。声明接口中定义的类型的变量,然后将该变量分配给其自己的类型对象的正确方法是什么。
let tempCompany = Company|undefined;
// I get error if I remove undefined in above line.
// Company is an interface with many properties
tempCompany = this.someArrayOfCompanies.find(x => x.zipCode === 65432);
if (tempCompany !== undefined) {
// error if I do not do this if check in above line
console.log(tempCompany.SalesFigure);
}
Run Code Online (Sandbox Code Playgroud)
更新:根据下面的反馈可能的答案。对于像我这样从 .Net/C# 转向 TS 的新手来说,会产生困惑,因为在 C# 中,我们将接口命名为 IAnimal(),然后有一个名为 Dog 的类实现 IAnimal()。在 TS 中,我们有 Animal 接口(没有 I),它的命名是为了让 TS 智能感知能够在 VS Code 中工作。另外,当你的 api 进入 Angular 时,它会返回一个 Animal 类型的可观察列表。基本上 TS 比 JS 好,但仍然存在所有这些疯狂的东西。
也许这个小例子会让你明白一些事情。
interface Animal {
legs: number;
}
var dog: Dog = { legs: 4 };
type canine = typeof dog;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6192 次 |
| 最近记录: |