Version: 14.4.2
index.d.ts file contents:
export {}
declare global {
export interface Person { name: string }
export type People = Person[]
}
Code I'm using to insert new interface into global namespace:
const globalNode = definitionsFile.getNamespace('global')
if (!globalNode) throw new Error('globalNode not found')
globalNode.insertText(globalNode.getEnd(), 'export interface Car { model: string }')
Expected: new interface to be inserted
Actual: Error thrown: _"Cannot insert or replace text outside the bounds of the node. Expected a position between [36, 41], but received 42."_
I also tried to use globalNode.getEnd() -1 - it just gives different error.
FYI, just checked, if global namespace is empty (no declared interfaces or types), it also gives this error, just with different position number.
I wonder if there any quick workaround? In my case I just need to add new interfaces to global namespace, but I have them as string like this:
export interface Person {
name : string // min(2), max(30)
age : number // min(0), max(160)
}
I could use globalNode.addInterface() which works fine, but I need to
So may be there is a way to provide a string like that and easily convert it to format that globalNode.addInterface() could use?
The code doesn't work because the text is being inserted outside the namespace (at the end position, which is after the namespace's closing brace).
If you don't want to use addInterface/addInterfaces then try using addStatements or insertStatements:
const globalNode = definitionsFile.getNamespaceOrThrow('global')
globalNode.addStatements('export interface Car { model: string }');
// another example, but using a writer
globalNode.addStatements(writer => {
writer.write('export interface Person').block(() => {
writer.writeLine('name : string, // min(2), max(30)')
.writeLine('age : number // min(0), max(160)');
});
});
@dsherret addStatements() works perfect, thanks!
Just in case if I'll have to use insertText() anywhere else, how do I get correct position of namespace at the end of the block to add text to?
@ihorskyi I just tried this out and you're right that this wasn't working properly! It should just be by doing -1 to go to the left of the close brace like you said.
It's a little difficult because you have to handle the spacing yourself:
globalNode.insertText(globalNode.getEnd() - 1, writer => {
writer.indent().write('export interface Car { model: string }').newLine();
});
That doesn't work right now, but it will be working in the next release. Thanks for reporting this!
Fixed in 14.4.3.