The challenge lies in TypeScript's approach to ensuring type safety, which restricts the use of unknown strings with bracket notation for object property lookups by default to prevent bypassing type checks.
To address this issue, there are a few options available:
Restrict Parameter Type
You can narrow down the parameter type to only accept values known to be valid properties of the object:
const slides = {
"barkingRoadProject": ['boomerang-site1.jpg', 'boomerang-site2.jpg', 'boomerang-site3.jpg']
}
export const SlideSupply = (slideName: keyof typeof slides): string[] => {
return slides[slideName];
}
Playground link
Keep in mind that SlideSupply
can only be called with a string known at compile-time to be a valid property name from slides
. Therefore,
SlideSupply("barkingRoadProject")
will work, but
SlideSupply(someString)
will not if
someString
is just any arbitrary string.
Type Assertion Function
To assure TypeScript of the validity of a string variable, you can create a type assertion function that confirms the variable contains known valid values:
function assertValidSlideName(slideName: string): asserts slideName is keyof typeof slides {
switch (slideName) {
case "barkingRoadProject":
case "any-other-valid-name-here":
break;
default:
throw new Error(`Invalid slide name "${slideName}"`);
}
Then modify SlideSupply
as follows:
export const SlideSupply = (slideName: string): string[] => {
assertValidSlideName(slideName); // ***
return slides[slideName];
}
Playground link
Alternatively, you can constrain SlideSupply
to only accept keyof typeof slides
and invoke the type assertion function before calling it.
Using String Index Signature
If desired, you can allow usage of any string value by implementing a string index signature for slides
:
const slides: {[key: string]: string[]} = {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
"barkingRoadProject": ['boomerang-site1.jpg', 'boomerang-site2.jpg', 'boomerang-site3.jpg']
}
export const SlideSupply = (slideName: string): string[] => {
return slides[slideName];
}
Playground link