我正在尝试使用RemoteObject
在Salesforce项目中使用typescript但是,我不确定如何为外部javascript对象的语法创建输入法。
javascript中使用代码的示例:
var ct = new RemoteObjectModel.Contact({
FirstName: "Aldo",
LastName: "Michaels",
Phone: "(415) 555-1212"
});
绊倒我的部分是new RemoteObjectModel.Contact()
。如何为此创建界面?
以下是我试图编译的代码示例
import React from 'react'
import ReactDOM from 'react-dom'
declare module RemoteObjectModel {
export class Account implements IRemoteObject {
constructor();
constructor();
get;
set;
}
}
interface IRemoteObject{
get(field: string): any;
set(field: string, value: string): any;
}
interface IAppProps{
remoteObjectModel: RemoteObjectModel
}
export class App extends React.Component<IAppProps, {}>{
public state : IAppState;
constructor(props : IAppProps) {
super(props);
this.state = {
accounts: 0
};
}
public render(){
let account: IRemoteObject = new this.props.remoteObjectModel.Account({
Name : 'hello!',
Active : true
});
console.log(account);
return (
<div>
New Accounts: {this.state.accounts}
Account: {account.get('Name')}
</div>
)
}
}
//set on the global state
declare var remoteObjectModel : IRemoteObjectModel;
ReactDOM.render(<App remoteObjectModel={remoteObjectModel} />, document.getElementById('app'));
这不起作用。 IAppProps
有错误:
消息:'找不到名称'RemoteObjectModel'。'
此外,我不确定我的问题标题是否正确反映了问题(如果没有,请更新!)
答案 0 :(得分:1)
如果将RemoteObjectModel
定义为类,则确实无法在其中定义嵌套类Contact
。
但是,您可以使用typescript的declaration merging功能 - 您可以将名称空间RemoteObjectModel
与同名的类(或接口)一起声明,并在该名称空间中声明类Contact
(不要忘记export
否则它将无法在命名空间外看到。
然后,粗略地说,只要打字稿单独看到RemoteObjectModel
,它就会引用该类,每当它看到RemoteObjectModel.something
时,它就会引用命名空间。
这样的事情:
class RemoteObjectModel {
someProperty: string;
constructor() {
this.someProperty = 'someValue';
}
}
namespace RemoteObjectModel {
export class Contact {
FirstName: string;
LastName: string;
Phone: string;
constructor(values: ContactProperties) {
Object.assign(this, values);
}
}
}
interface ContactProperties {
FirstName: string;
LastName: string;
Phone: string;
}
var ct = new RemoteObjectModel.Contact({
FirstName: "Aldo",
LastName: "Michaels",
Phone: "(415) 555-1212"
});
此外,您可以在RemoveObjectModel
课程中定义constructor signature,允许您拨打new remoteObjectModel.Contact()
,就像在实例上定义Contact
一样:
class RemoteObjectModel {
someProperty: string;
Contact: {new(p: ContactProperties): RemoteObjectModel.Contact}
}
namespace RemoteObjectModel {
export class Contact {
FirstName: string;
LastName: string;
Phone: string;
constructor(values: ContactProperties) {
Object.assign(this, values);
}
}
}
interface ContactProperties {
FirstName: string;
LastName: string;
Phone: string;
}
const remoteObjectModel = new RemoteObjectModel();
var c2 = new remoteObjectModel.Contact({
FirstName: "Aldo",
LastName: "Michaels",
Phone: "(415) 555-1212"
});
或者,您可以声明实例属性Contact
,其类型为&#39;静态部分&#39; Contact {(可以用作构造函数),使用typeof Contact
:
class RemoteObjectModel {
someProperty: string;
Contact: typeof RemoteObjectModel.Contact
constructor() {
this.Contact = RemoteObjectModel.Contact;
}
}