如何在TypeScript中声明类似嵌套对象的JavaScript?
let endpoints = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
以下不起作用:
private endpoints: Object = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
抛出:
error TS2339: Property 'auth' does not exist on type 'Object'.
答案 0 :(得分:20)
您可以使用界面:
interface EndpointAuth {
login: string;
}
interface Endpoint {
auth: EndpointAuth;
}
let endpoints: Endpoint = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
您也可以使用类型而不是接口:
type EndpointAuth = {
login: string;
}
type Endpoint = {
auth: EndpointAuth;
}
或"内联":
let endpoints: { auth: { login: string } } = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
当然,你可以将它们结合起来。
正如您想要的答案解释为什么它不适用于Object
:
将变量定义为Object
类型(在大多数情况下)不是你真正想要做的,通常你的意思是any
,因为:
var endpoints2: any = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
不会失败(就像你没有指定类型一样赢了)。
将变量定义为Object
与将{}
定义为空对象相同,并且通常不是您之后所做的,并且它仅适用于所有内容像:
let o1: Object = {};
let o2: Object = Object.create(null);
但是使用any
并不能帮助你太多,因为那时你基本上告诉编译器不要打扰类型安全,它会让你用变量做任何事情而不让你知道有错误:
let o: any = { x: 3, y: 6 };
console.log(o.z.toString());
在编译中失败但在运行时会失败:
未捕获的TypeError:无法读取属性' toString'未定义的
这将在编译中失败:
let o: { x: number, y: number } = { x: 3, y: 6 };
console.log(o.z.toString());
答案 1 :(得分:3)
如果您想要类型安全,需要创建自定义类\ interface:
interface IMyInterface
{
auth: IAuth;
}
interface IAuth
{
login: string;
}
private endpoints: IMyInterface= {
auth: {
login: "http://localhost:8079/auth/login"
}
};
您的错误是因为您声明的Object类型的端点和Object没有auth属性。
答案 2 :(得分:3)
您可以声明一个接口。
对于你的情况
interface IEndpoints
{
auth: {
login: string;
}
}
private endpoints: IEndpoints = {
auth: {
login: "http://localhost:8079/auth/login"
}
};
答案 3 :(得分:2)
我不知道您过去使用的打字稿版本,但是目前支持该版本
interface Endpoints {
[path: string]: Endpoints | string
}
const endpoints: Endpoints = {
auth: {
login: "http://localhost:8079/auth/login"
}
}