Ad
How To Make A Dynamic Key Optional With Typescript
I would like to make the dynamic key item
optional. Adding ?
creates an error.
type Example = {
name?: string;
[item: string]?: unknown; // error: TS1131: Property or signature expected.
};
Ad
Answer
You can use the type utilitiesPartial
and Record
to create the type you want:
type Example = Partial<Record<string, unknown>> & { name?: string };
declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown
Ad
source: stackoverflow.com
Related Questions
- → .tsx webpack compile fails: Unexpected token <
- → Angular 2 bootstrap function gives error "Argument type AppComponent is not assignable to parameter type Type"
- → AngularJS Two binding in directive
- → How to fix "TS2349: Cannot invoke an expression whose type lacks a call signature"
- → Typescript point to function
- → Manage 301 Redirect when moving oldsite to AngularJS
- → Why is "this" null, in the link function within an Angular Directive?
- → ES6 equivalent of this Angular 2 typescript
- → Where to find example Visual Studio 2015 project(s) using typescript and React?
- → typescript definition for react-router v2.0 - error `has no exported member 'browserHistory'`
- → what version of javascript does typescript compile to?
- → How to configure Visual Studio 2015 to write JSX in ASP.NET 5 (RC) with intellisense
- → what's the different between ///<reference path="..."/> and import statement
Ad