What is the best way to retrieve property names that are not nullable from a type?

I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null. For example:

interface Person {
   name: string
   age: number 
   category: string | null
}

type NotNullablePersonProps = NotNullablePropertyNames<Person> 
// Expected output: "name" | "age"

I came across an example on GitHub that introduces the concepts of Optional and Required Property Names:

type OptionalPropertyNames<T> = {
    [K in keyof T]-?: undefined extends T[K] ? K : never
}[keyof T];

type RequiredPropertyNames<T> = {
    [K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T];

While this example is helpful, I struggled to modify it to account for properties with a value of null.

How should I define a NotNullablePropertyNames mapped conditional type to accurately return all property names that cannot be null?

Answer №1

When you replace undefined with null in the given code snippet, it functions as expected if you have the strictNullChecks option enabled. Otherwise, when the option is not set, string | null is essentially just string, rendering nothing to extract.

interface Person {
   name: string
   age: number 
   category: string | null
}

type NotNullablePersonProps = NotNullablePropertyNames<Person> // name | age

type NotNullablePropertyNames<T> = {
    [K in keyof T]-?: null extends T[K] ? never : K
}[keyof T];

Access playground here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am working on an Angular application that includes a dynamic form for an attendance system for employees. I am currently trying to figure out how to generate the JSON data

I have a dynamic form in my reactive attendance system for employees. When I click on submit, I need to generate JSON data like the following: { "user_id": "1", "branch_id": "4", "auth_token": "59a2a9337afb07255257199b03ed6076", "date": "2019- ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: I have succ ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

Using Angular 2's ngModel directive to bind a value passed in from an

Using [(ngModel)] in my child component with a string passed from the parent via @Input() is causing some issues. Although the string is successfully passed from the parent to the child, any changes made to it within the child component do not reflect bac ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...

Using optional function arguments with destructured arguments in TypeScript can result in throwing an error

interface Type1 { attr1: string; attr2: string; } interface Type2 { attr1: string; attr2: string; attr3: string; // additional attribute } function fn(config: Type1 | Type2): void { // The error code is displayed above. I am ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

Is it possible to create a tuple with additional properties without needing to cast it to any type?

To accommodate both array and object destructuring, I have defined the following `Result` type: type Errors = Record<string, string | null>; type Result = [Errors, boolean] & { errors: Errors; success: boolean }; I attempted to create a result of t ...

Having trouble sending an email using nodejs and mailgun

Before accusing me of asking a duplicate question, I want to clarify that I have already searched for solutions and none of them worked for me. For example, I tried the solution provided in this link: Example of the domain name for mailgun before nodejs? ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...

Ways to input a return value that may be an array depending on the input

I'm struggling to properly type the return value in TypeScript to clear an error. function simplifiedFn( ids: string | string[], ): typeof ids extends string[] ? number[] : number { const idsIsArray = Array.isArray(ids); const idsProvided = idsI ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Typescript sometimes struggles to definitively determine whether a property is null or not

interface A { id?: string } interface B { id: string } function test(a: A, b: A) { if (!a.id && !b.id) { return } let c: B = { id: a.id || b.id } } Check out the code on playground An error arises stating that 'objectI ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

My goal is to intentionally trigger an eslint error when importing a file from index.ts

Is there a way to enforce importing components from index.ts within the src/components directory using eslint rules or plugins? // index.ts (src/components/Forms) export { Input } from './Input'; export { CheckBox } from './CheckBox'; ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

I'm struggling to get a specific tutorial to work for my application. Can anyone advise me on how to map a general URL to the HTTP methods of an API endpoint that is written in C

I am struggling to retrieve and display data from a C# Web API using Typescript and Angular. As someone new to Typescript, I followed a tutorial to create a service based on this guide: [https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest- ...