Skip to content

Commit df03df8

Browse files
authored
fix(core): Duration.toString() throws an error (#18243)
`Duration.toString()` was intended to produce a value that would throw an exception when resolved, but unintentionally was written to always throw immediately (the reason it was throwing is that `Token.asString()` doesn't accept functions, it only accepts data values--`Lazy.string()` should have been used). Instead, we remove the validation completely. `toString()` now produces a meaningless string, and users should avoid using the `Duration` object in a context where it will be implicitly converted to a string. Fixes #18176. ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent 2868f1d commit df03df8

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

packages/@aws-cdk/core/lib/duration.ts

+5-9
Original file line numberDiff line numberDiff line change
@@ -220,17 +220,13 @@ export class Duration {
220220
}
221221

222222
/**
223-
* Returns a string representation of this `Duration` that is also a Token that cannot be successfully resolved. This
224-
* protects users against inadvertently stringifying a `Duration` object, when they should have called one of the
225-
* `to*` methods instead.
223+
* Returns a string representation of this `Duration`
224+
*
225+
* This is is never the right function to use when you want to use the `Duration`
226+
* object in a template. Use `toSeconds()`, `toMinutes()`, `toDays()`, etc. instead.
226227
*/
227228
public toString(): string {
228-
return Token.asString(
229-
() => {
230-
throw new Error('Duration.toString() was used, but .toSeconds, .toMinutes or .toDays should have been called instead');
231-
},
232-
{ displayHint: `${this.amount} ${this.unit.label}` },
233-
);
229+
return `Duration.${this.unit.label}(${this.amount})`;
234230
}
235231

236232
/**

packages/@aws-cdk/core/test/duration.test.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import { Duration, Lazy, Stack, Token } from '../lib';
44
describe('duration', () => {
55
test('negative amount', () => {
66
expect(() => Duration.seconds(-1)).toThrow(/negative/);
7+
});
78

8-
9+
test('can stringify', () => {
10+
expect(`${Duration.hours(1)}`).toEqual('Duration.hours(1)');
911
});
1012

1113
test('unresolved amount', () => {

0 commit comments

Comments
 (0)