Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return single item or item[] based on thing #80

Merged
merged 1 commit into from
Apr 11, 2023
Merged

Conversation

kearfy
Copy link
Member

@kearfy kearfy commented Apr 11, 2023

Motivation

Currently, the helper functions simply return either a single item or an array of items.
This PR is not optimal, but the best way to handle this as far as I can see.

How does this PR work?

Essentially, when you define a variable:

const userId = 'user:tobie';

Then typescript is smart enough to be able to compare it against a type like:

type Thing = `${string}:${string}`;

// Hint: The type is true :)
type userIdIsThing = 
    (typeof userId) extends Thing ? true : false; 

Put it to practice

import { Surreal, Thing } from 'surrealdb.js';

const surreal: Surreal;
type User = {
    id: Thing;
    name: string;
};

// Returns type "User[]" (as a promise)
const result = await surreal.select<User>('user');

// Returns type "User" (as a promise)
const result = await surreal.select<User>('user:tobie');

// Downside is that if the type is not clear, you'll have to force the type yourself if you know that it's of type "string:string"
// When you store a variable as a plain text in your code, typescript is smart enough to resolve the contents of the string
// Assume params is of type "Record<string, string>"
const { user } = params;

// Returns type "User" (as a promise)
const result = await surreal.select<User>(user as Thing);
// OR...
const result = await surreal.select<User, Thing>(user);

@kearfy kearfy self-assigned this Apr 11, 2023
@kearfy kearfy added bug Something isn't working enhancement New feature or request labels Apr 11, 2023
@kearfy kearfy linked an issue Apr 11, 2023 that may be closed by this pull request
@kearfy kearfy merged commit fc2733d into main Apr 11, 2023
4 checks passed
@kearfy kearfy deleted the micha/type-returns-thing branch April 11, 2023 14:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat: change function should return allways an array
1 participant