Giter Club home page Giter Club logo

type-fest's Issues

Optional Values of Type

Anyone know if its possible to get the Optional values of a type?

interface A {
  a: string;
  b?: string;
  c?:string;
  d: string;
}

type B = OptionalsOf<A>;

so B becomes something like

type B = {
  b?: string;
  c?: striing;
};

Though for my usecase I will do something like

type B = Required<OptionsOf<A>>;

But I presume that wouldn't make a difference?

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Possible improvement of Omit

type Omit<ObjectType, Keys> = Pick<
    ObjectType,
    Exclude<keyof ObjectType, Keys extends Primitive ? Keys : keyof Keys>
>

Example:

// Primitive example
type A = Omit<{ a: 1, b: 2, c: 3 }, 'a' | 'b'>
// => { c: 3 }

// Object example
type B = Omit<{ a: 1, b: 2, c: 3 }, {a: true, b: 'a'}>
// => { c: 3 }

What do you think?

Proposal: ThenArg

Hey there,

would be nice to include the helper type to unwrap a PromiseLike:

e.g.

type ThenArg<T> = T extends Promise<infer U> ? U : T

my main motivation is when using jsdoc in js I often declare a let without any initialisation and assign a value in a later closure (mostly when running mocha tests), e.g.:

describe('some block', () => {
  /** @type {ThenArg<ReturnType<loadData>>} */
  let data; // <-- data is untyped if not defining the @type above
  before('load data', async () => {
    // loadData is typed here and returns a valid type, but data keeps being set to any
    data = await loadData();
  })

  it('has loaded to correct data', () => {
    // ...
  });
})

Opaque types are interchangeable

Do you have any examples for Opaque? I thought Opaque types weren’t supposed to be interchangeable.

import { Opaque } from 'type-fest';

type AccountNumber = Opaque<number>;
type AccountBalance = Opaque<number>;

function getBalance(accountNumber: AccountNumber): AccountBalance {
  return 101 as AccountBalance;
}

// pass an AccountBalance instead of an AccountNumber
const ab = 42 as AccountBalance;
console.log(getBalance(ab)); 
// expected: should not compile
// actual: gets balance for account 42

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Improve documentation and tests

My goal is to have the best documentation for each provided type.

If something is unclear in any of the types, please comment or open a PR to improve it.

Some things you could contribute:

  • Fix typos.
  • Improved description of the type.
  • More examples.
  • Provide more real-world use-cases. This helps the user understand where a type might come in handy.
  • Add links to relevant discussions and docs/tutorials about a type from around the internet.
  • Explain the types.
  • More tests.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

`Opaque` forces lookup to `any` type because it cannot be used to index `Record` type

I use Opaque type extensively to reduce type errors for strings, but I found out that it has an unexpected behaviour that it cannot be used as a Record's index type.
Please see the example below for a typical setup.

import { Opaque } from 'type-fest';

type UUID = Opaque<string, 'UUID'>
type NormalizedDictionary<T> = Record<UUID, T>

type Foo = { bar: string }

const userEntities: NormalizedDictionary<Foo> = {
  '7dd4a16e-d5ee-454c-b1d0-71e23d9fa70b': { bar: 'John' },
  '6ce31270-31eb-4a72-a9bf-43192d4ab436': { bar: 'Doe' },
}

const johnsId = '7dd4a16e-d5ee-454c-b1d0-71e23d9fa70b' as UUID

const userJohn = userEntities[johnsId]
// the type of userJohn is `any`

Can anyone provide me a way to use an Opaque type to index a Record without sacrificing the type of the value becoming any?

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: OneOrMore

type OneOrMore<T> = T | T[];

lodash also has this type named as Many.

This is useful when you have a complex type:

OneOrMore<Validator<Value> | null>

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Documentation improvement request: Merge versus intersection

Recently someone pushed this commit to Got with the following message:

Use Merge as it's stricter than the intersection operator

I came here looking for an explanation on what exactly this means, and found none. I noticed that Merge uses the intersection operator under the hood, but I'd like to understand this better. Thanks.

Relates to #8

Also seems very related to this question I asked on SO recently (in which coincidentally I invented the terminology merged type before noticing the existence of Merge here in type-fest)

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

`AsyncReturnType` doesn't work with arguments

I'm not able to use this type:

type PromisedStringFunction = (query: string) => Promise<string>;
type ShouldBeAString = AsyncReturnType<PromisedStringFunction>;

I get this error:

Type '(query: string) => Promise<string>' does not satisfy the constraint 'AsyncFunction'.
  Types of parameters 'query' and 'args' are incompatible.
    Type 'unknown' is not assignable to type 'string'.ts(2344)

I had my own AsyncReturnType and it worked well with any, not unknown

Proposal: FlipOptional

type OptionalKeys<T> = {
  [K in keyof T]-?: {} extends Pick<T, K> ? K : never
}[keyof T];

type FlipOptional<T> = (Required<Pick<T, OptionalKeys<T>>> &
  Partial<Omit<T, OptionalKeys<T>>>) extends infer O
  ? { [K in keyof O]: O[K] }
  : never;

Taken from https://stackoverflow.com/a/57593506/1154610.

A practical example is a TypeScript equivalent of ESLint rule react/require-default-props.

import React from 'react';

export interface InputProps {
  className?: string;
  name: string;
}

export default class Input extends React.Component<InputProps> {
  static defaultProps: FlipOptional<InputProps> = {
    // className is required for defaultProps.
    className: null
    // name is optional for defaultProps.
  }

  render() {
    const { className, name } = this.props;

    return <input className={className} name={name} />
  }
}

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: PartialExcept

I've recently made the following type, and I though it might be useful enough to be included here:

type PartialExcept<Object, Keys extends keyof Object> = Partial<Object> & {
  [Key in Keys]: Required<Pick<Object, Key>>[Key]
};

It makes all properties in Object optional, except for the properties specified in Keys, which are required.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Add `Optional` type

An optional type is really missing in the context of return types,
When a function might a value or not you find yourself piping undefined

type Maybe<T> = T | undefined;

Can be really useful

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Add examples for the built-in types mentioned in the readme

Issuehunt badges

I made a section in the readme for useful built-in types that many TS devs don't know about. Would be useful to also include some real-world examples of those types in use. It's hard to realize when they would be useful just from their description.

https://github.com/sindresorhus/type-fest#built-in-types

To resolve this issue you should at least add one realistic example for each type.


IssueHunt Summary

krnik krnik has been rewarded.

Backers (Total: $60.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: SubType

 type SubType<Base, Condition> = Pick<
     Base,
     {
         [Key in keyof Base]: Base[Key] extends Condition ? Key : never
     }[keyof Base]
 >;

Examples:

var object = {
    a: 1,
    b: true,
    c: () => null,
    d: () => null,
};

type JustMethods = SubType<typeof object, (...args: unknown[]) => unknown>;
// { c: () => null, d: () => null }

JustMethods from #4 can be realized via SubType. But, as I understand, JustProps can't. Maybe it will be possible after microsoft/TypeScript#29317

Proposal: `PlainObject`

Motivation/Use-cases

If you want to model an object that can accept anything as value, you're tempted to use one of the following approach:

const myObject: { [props: string]: any } = { foo: 'bar' }  

or

const myObject: Record<string, any> = { foo: 'bar' }  

The problem being that both { [props: string]: any } and Record<string, any> accept functions and arrays, which I believe in 99% of cases is not what you were trying to model with your type. (Playground showcase here)

Proposal

We could construct a safer type based on the existing primitives of type-fest:

import { Primitive } from 'type-fest'

/**
 * Represents a POJO. Prevents from allowing arrays and functions
 */
export type PlainObject = {
  [x: string]: Primitive | object
}

Playground Example here

Notes

  • The fact that it's very easy to construct with the existing type-fest primitives might be a case for not adding it, open for discussion

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: AsyncReturnType

Reason

TypeScript provides ReturnType to infer what type a function returns, but it isn't as as useful when functions return a promise and you want to know what type the promise resolves to.

Proposal

ResolvedType which returns the type of a function that returns a promise, but also works if the function is not a promise.

Example

// Silly simple example
const asyncFunction = async (n: number) => n * 2;

// We have this today
type AsyncFunctionReturns = ReturnType<typeof asyncFunction>;
// => Promise<number>

// This is the proposal
type AsyncFunctionReturns = ResolvedType<typeof asyncFunction>;
// => number

Proof of concept

Not tested extensively, may have bugs!

// For any function, return the returnType or promiseResolved type.
export type ResolvedValue<FuncPromOrValue> = FuncPromOrValue extends (...args: any) => any
    ? ReturnType<FuncPromOrValue> extends Promise<infer Result> // Is a function.
        ? Result // Is a promise, return result from Promise.
        : ReturnType<FuncPromOrValue> // Non-promise function, return result.
    : FuncPromOrValue; // Not a promise or function, return type.

Existing work

I haven't seen anything like this before, but that doesn't mean it doesn't exist. I'm not fluent with other typed languages to know if there's a reason this doesn't exist or better way to implement it.

Cannot find name 'unknown'.

platform: win10

ERROR in node_modules/type-fest/index.d.ts(20,23): error TS2304: Cannot find name 'unknown'.
node_modules/type-fest/index.d.ts(61,30): error TS2304: Cannot find name 'unknown'.
node_modules/type-fest/source/package-json.d.ts(60,28): error TS2304: Cannot find name 'unknown'.
node_modules/type-fest/source/package-json.d.ts(375,24): error TS2304: Cannot find name 'unknown'.
node_modules/type-fest/source/package-json.d.ts(486,21): error TS2304: Cannot find name 'unknown'.
node_modules/type-fest/source/package-json.d.ts(493,17): error TS2304: Cannot find name 'unknown'.

How to use `JsonObject`?

const json: JsonObject = await fetchJson(...);
console.log(json.a.b.c);

// => error TS2339: Property 'b' does not exist on type 'string | number | boolean | JsonObject | JsonArray'.
  Property 'b' does not exist on type 'string'.

It seems to be useful for one-level JSON, but after that you'll have to use as JsonObject at every level, if you want to access a deep property (e.g. GraphQL response)

Proposal: DeepRecord

A while back while working on a project we needed a generic function to slice all strings of the provided object.

const stringSlicer = <T, U> (data: T, checker: U): T => {};

We wanted the U type the have the same type as the first argument but it had to flatten all the arrays.
So if T was of type

interface T {
	name: string;
	items: {
 		id: string
	}[]
}

U had to be of type

interface U {
	name: number;
	items: {
		id: number;
	}
}

With interface U defining the length of each string. But it shouldn't provide an array for items

proposal

export type DeepRecord<K, T> = {
	[P in keyof K]:
		Exclude<K[P], undefined> extends Array<infer E> ? DeepRecord<E, T> :
		Exclude<K[P], undefined> extends object ? DeepRecord<K[P], T> :
		T;
};

This way we can write the function as following

const stringSlicer = <T> (data: T, checker: DeepRecord<T, number>): T => {};

Add `WithReturnType` type?

type WithReturnType<
  TFn extends (...args: any) => any,
  TR
> = TFn extends (...args: infer TArgs) => any ? (...args: TArgs) => TR : any;

Creates a new function type that replaces the given function type's return type with the given type.

Use case: functions that return wrapped callbacks, i.e. any generic function in the general form of

(cb: (...args: A) => any) => (...args: A) => B

e.g. here's a React hook:

function useAsync<TFn extends (...args: any) => Promise<any>>(
  asyncFn: TFn
): [
  { loading: boolean; result?: AsyncReturnType<TFn> },
  WithReturnType<TFn, Promise<void>>
] {
  const [state, setState] = React.useState({
    loading: false,
    result: undefined as AsyncReturnType<TFn> | undefined
  });
  return [state, (async (...args: any) => {
    setState({ ...state, loading: true });
    try {
      const result = await asyncFn(...args);
      setState({ ...state, loading: false, result });
    } catch (e) {
      setState({ ...state, loading: false });
    }
  }) as WithReturnType<TFn, Promise<void>>];
}

I'm not sure if this use case is widespread enough but the solution is non-obvious if you're not familiar with conditional types (it's derived from how ReturnType is defined). I can create a PR if there's interest in adding this.

Proposal: Promisable

Some times we are just awaiting a function, so we don't really care if the returned value is actually a promise or not. With Promisable:

type Promisable<T> = T | Promise<T>;

One could write this:

type Foo = () => Promisable<string | number | null>

Rather than:

type Foo = () => string | number | null | Promise<string> | Promise<number> | Promise<null>

It helps write a bit cleaner code. I'm not sure if it's useful enough to be included here, but I thought I'd mention it.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Rename `Omit`

We managed to convince the TS team to add Omit as a built-in type, unfortunately, they added a loose version, not what we suggested, and they insist on staying with it.

The great thing about user-land code is that we can fix their dumb decisions.

However, that does mean our Omit type will conflict with the native one... But I guess that gives us the opportunity to come up with a better name for it.

I never really found Omit that clear. How about ExcludeProperty or ExcludeKey? I prefer the former. Open to other suggestions.

PackageJson - recommendation for extending the interface

The package.json definition is a great start, but going to be impossible to include everything.

We can make PR's for every field that is missing (yarn is missing workspaces, for example), but this could become never-ending, such as supporting package.json-based config for jest.

Instead, maybe it would be useful to document how we recommend developers extend the existing definition to add types they need for their code.

I'm still learning TypeScript, so I'm not sure if the best practice is for developers to provide extended properties in a global PackageJson namespace in a d.ts file, or use generics to pass in someting like PackageJson<extraFields>.

Thoughts?

`RequireAtLeaseOne` issues

import { RequireAtLeastOne } from 'type-fest';

interface BaseConditionProps {
  when: string;
  is?: any;
  isNot?: any;
  children: (value: any) => React.ReactNode;
}

type ConditionProps = RequireAtLeastOne<BaseConditionProps, 'isNot' | 'is'>;

const Condition: React.FC<ConditionProps> = ({ when, is, isNot, children }) => (  // ERROR HERE
  <Field name={when} subscription={{ value: true }}>
    {({ input: { value } }) => {
      const show = is ? value === is : value !== isNot;
      return show ? children(value) : null;
    }}
  </Field>
);

Typescript complain that

  1. Property 'isNot' does not exist on type 'PropsWithChildren<RequireAtLeastOne<BaseConditionProps, "is" | "isNot">>'.ts(2339)
  2. Property 'is' does not exist on type 'PropsWithChildren<RequireAtLeastOne<BaseConditionProps, "is" | "isNot">>'.ts(2339)

I had no problem if I use another version that I found in the issue.

import { Except } from 'type-fest';

export type RequireOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> = {
  // For each Key in KeysType make a mapped type
  [Key in KeysType]: (// …by picking that Key's type and making it required
  Required<Pick<ObjectType, Key>> &
    // …and adding the other keys in KeysType as optional and of type `never`
    Partial<Record<Exclude<KeysType, Key>, never>>);
}[KeysType] &
  // …then, make intersection types by adding the remaining properties to each mapped type.
  Except<ObjectType, KeysType>;

Proposal: Constructor

I propose the following "Constructor" interface:

interface Constructor<Class, Args extends any[] = []> {
  new ( ...args: Args ): Class
}

The problem it solves is the following.

Let's say we have the following Foo class:

class Foo {}

If we need to accept a Foo class as an argument we can write something like this:

function fn ( cls: typeof Foo ) {}

But what if Foo is a generic class? Then we can't write something like this:

function fn ( cls: typeof Foo<any> ) {}

And we also can't just write something like this:

function fn ( cls: Foo<any> ) {
  new cls ();
}

Because cls won't be recognized as a constructor and TS will throw the following error:

Cannot use 'new' with an expression whose type lacks a call or construct signature.ts(2351)

Here's where the proposed Constructor interface comes in, with it we can write the following:

class Foo<T1, T2> {}

function fn ( cls: Constructor<Foo<any, any>> ) {
  new cls ();
}

Apparently this has been discussed already in TypeScript's repo, here, and somebody mentioned how Angular also had to define a similar interface.

I've already stumbled on this twice, here and in another library I haven't released yet.

Proposal: ExcludeProps

@webstrand came up with this pretty cool type which I modified a bit, basically it's useful when you want to ensure that some properties are not set in an object.

In this real case scenario we want to extend a class instance with an object, but the properties set in said object mustn't override any already known properties, in order to avoid conflicts, so we use ExcludeProps for enforcing this:

// ExcludeProps definition

type ExcludeProps<T> = { [P in keyof T]?: 'Error: You cannot use this particular property name' & number } & { [prop: string]: any; };

// Usage 

class Foo {
  myProp: number = 123;
  protected myProtectedProp: number = 123;
  constructor ( extraProps: ExcludeProps<Foo> ) {
    Object.assign ( this, extraProps );
  }
}

new Foo ({ foo: 123 }); // It works, `foo` is not an excluded property

new Foo ({ myProp: 123 }); // We get an error, `myProp` is not allowed as it conflicts with the already known `myProp` property of Foo

new Foo ({ myProtectedProp: 123 }); // Unfortunately private e protected props aren't properly supported

I thought maybe it could be a decent addition to this repo, or maybe it's not general/useful enough, what do you think?

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Docs: Partial Example Error from v3.5.1

Partial Example: error from 3.5.1

interface NodeConfig {
 		appName: string;
 		port: number;
 }

 class NodeAppBuilder {
 		private configuration: NodeConfig = {
 				appName: 'NodeApp',
 				port: 3000
 		};

 		config(config: Partial<NodeConfig>) {
 				type NodeConfigKey = keyof NodeConfig;

 				for (const key of Object.keys(config) as NodeConfigKey[]) {
 						const updateValue = config[key];

 						if (updateValue === undefined) {
 								continue;
 						}

 						this.configuration[key] = updateValue;
 				}

 				return this;
 		}
 }

 // `Partial<NodeConfig>`` allows us to provide only a part of the
 // NodeConfig interface.
 new NodeAppBuilder().config({appName: 'ToDoApp'});
Type 'string | number' is not assignable to type 'string & number'.
  Type 'string' is not assignable to type 'string & number'.
    Type 'string' is not assignable to type 'number'.

playground example

https://www.typescriptlang.org/play/?ts=3.3.3#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClbOAUQAFMWuHAAKcGLAcGoAPPH+rgB8AJSh4chgAJ50KC0uxADSEH3ByADWE+gwOn4jAiphNDCiyOX43DMTyPPIAPIyAFYQCGAAdLN9nNslXZqLuMvjfQDaALpdFGvhxV2kjomAcEAAag1JCgQhViB9bl9Cv8aMAFqVgaDIJC1NDgkEQpIQNhCCAIJhfqkek58GBQNCFNTkMpKFSaGAABbAThXOFuDx0-AIiZfKaYsE46FUllUqAQMDuEC9LmcRnMqgsoA

I would submit pull request but my typescript journey is just beginning; nut shell either typescript bug or from 3.5.1 strictness on this is tighter. But for me both types are string | number| so πŸ€·β€β™‚

Proposal for ModifyType ?

I find myself utilizing this useful type often for overriding a root type's fields with a different type.

https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file#answer-55032655

Impl Type

type ModifiedType = Modify<OriginalType, {
  a: number;
  b: number;
}>

Example:

interface OriginalType {
  a: string;
  b: boolean;
  c: number;
}

type ModifiedType  = Modify<OriginalType , {
  a: number;
  b: number;
}>

// ModifiedType = { a: number; b: number; c: number; }

Would you all consider adding this or is there an existing suitable type in here already?

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Suggestion: NonEmptyArray

The following type looks really interesting:

type NonEmptyArray<A> = A[] & {0: A};

The original discussion was brought up in this thread: gcanti/fp-ts#735

If there's interest I could raise a PR.

Proposal: Dictionary

Define

interface Dictionary<T> {
    [key: string]: T;
}

Usage

let v1: Dictionary<number>;
let v2: Dictionary<string>;
let v3: Dictionary<any>;

This is a very common and useful definition, also mentioned in the official documentation.

AsyncReturnType doesn't work

I'm not sure how AsyncReturnType is supposed to work. If I try it with a basic async function, that takes a string argument & returns it, I get a type error.

Type '(bar: string) => Promise' does not satisfy the constraint 'AsyncFunction'.
Types of parameters 'bar' and 'args' are incompatible.
Type 'unknown' is not assignable to type 'string'

I've set up a Codesandbox that demonstrates this. I'm not sure what Typescript version it's using, it's not listed in the dependencies, but I am getting it with TS v3.8.2 in my local project.

I'm not sure if there is a specific reason not to use any here, but replacing ...args: unknown[] with ...args: any[] in the AsyncFunction definition resolves the error.

JsonObject doesn't allow optionals

I want to type something as JsonObject, because the interface defines a request from an API.

So then I use extends JsonObject, but my API has some optionals.

interface Unicorn extends JsonObject {
	unicorn: string;
	rainbow?: string;
}

The compiler will fail with

Property 'unicorn' of type 'string | undefined' is not assignable to string index type 'JsonValue'

The reasoning behind this is that undefined is not serializable and doesn't exist in JSON. But how would someone solve this issue? Or should we change something in the JSON definitions of type-fest?

A possible solution would be to allow undefined in JsonObject.

export type JsonObject = {[key: string]: JsonValue | undefined};

This allows me to add optionals to something which is a JsonObject.

interface Unicorn extends JsonObject {
	unicorn: string;
	rainbow?: string;
}

To me, this kinda makes sense because JSON.stringify({unicorn: 'πŸ¦„', rainbow: undefined}) results in {"unicorn":"πŸ¦„"}, thus allowing undefined in JSON like objects.

Except not removing keys as Omit does

export interface Identifiable<T> {
  readonly id: T;
}

export interface Entity<ID> extends Identifiable<ID> {
  readonly createdAt: ZonedDateTime;
  modifiedAt: ZonedDateTime;
}

export type EntityOpts<T extends Entity<unknown>> = Omit<
  Partial<T>,
  'id' | 'createdAt' | 'modifiedAt'
>;

replace Omit with Except in this code and all of the "excluded" keys will still be available for use and compile.

> yarn list typescript type-fest && node --version
yarn list v1.22.4
warning Filtering by arguments is deprecated. Please use the pattern option instead.
β”œβ”€ @google-cloud/[email protected]
β”‚  └─ [email protected]
β”œβ”€ [email protected]
β”‚  β”œβ”€ [email protected]
β”‚  β”‚  └─ [email protected]
β”‚  └─ [email protected]
β”œβ”€ [email protected]
β”‚  └─ [email protected]
β”œβ”€ [email protected]
β”‚  β”œβ”€ [email protected]
β”‚  β”‚  └─ [email protected]
β”‚  β”œβ”€ [email protected]
β”‚  β”‚  └─ [email protected]
β”‚  └─ [email protected]
β”œβ”€ [email protected]
└─ [email protected]
✨  Done in 1.28s.
v12.16.3

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: Opaque

Please add support for opaque types, like so (here's a one liner):

type Opaque<V> = V & { readonly __opq__: unique symbol };

This would then be used like so:

type AccountNumber = Opaque<number>;
type AccountBalance = Opaque<number>;

function createAccountNumber (): AccountNumber {
    return 2 as AccountNumber;
}

function getMoneyForAccount (accountNumber: AccountNumber): AccountBalance {
    return 4 as AccountBalance;
}

// CompilerError:
getMoneyForAccount(2); 

// CompilerSuccess
getMoneyForAccount(createAccountNumber());

(copied from my gist)

This would be incredibly useful, and the TypeScript developers just don't seem like they're interested in implementing it.

`PackageJson` is not a valid `JsonObject`

Description

The following fails type checking.

import {PackageJson, JsonObject} from 'type-fest';
import {expectType} from 'tsd';

const packageJson: PackageJson = {};

const createPackageJson = () => packageJson;
expectType<JsonObject>(createPackageJson()); // => Error

The error produced is the following.

Argument of type 'PackageJson' is not assignable to parameter of type 'JsonObject'.
  Index signatures are incompatible.
    Type 'unknown' is not assignable to type 'JsonValue'.
      Type 'unknown' is not assignable to type 'JsonArray'.ts(2345)

To fix this we would need to remove unknown from the PackageJson type and replace it with JsonValue since the package.json file only supports valid Json this shouldn't cause any issues.

I'll create a PR shortly.

Proposal: DeepPartial

Issuehunt badges

interface Child {
  id: string;
  name: string;
  state: string;
  mother: {
    name: string;
    some: string;
  }
}

function fn(child: Partial<Child>) { }

fn({ name: '' }); // OK
fn({ mother: { name: '' }}); // NO, Property 'some' is missing

But.

type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> };

function fn(child: DeepPartial<Child>) { }

fn({ name: '' }); // OK
fn({ mother: { name: '' }}); // OK

How about this?


IssueHunt Summary

kainiedziela kainiedziela has been rewarded.

Backers (Total: $60.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Question: is there any way to get the advantages of opaque and other options at the same time?

given

export type OrderPart = SetRequired<Except<Partial<OrderEntity>, 'id'>, 'orderId'>;
export type OrderOnly = Opaque<OrderPart>;

export class OrderAggregateFactory {
  constructor(private readonly em: EntityManager) {}

  order(part: OrderOnly): Promise<OrderEntity> {

if I use it like this... I get the benefits of both

      const orderPart: OrderPart = {
        status: OrderStatus.Open,
        orderId,
      };
      return new OrderAggregateFactory(em).order(orderPart as OrderOnly);

but if I write like the latter, I lose the benefits of SetRequired, and probably other things (this compies)

      return new OrderAggregateFactory(em).order({
        status: OrderStatus.Open,
      } as OrderOnly);

is their a way to write it "like" the latter example? but still have Required and other things cause compile errors?

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: Partial/Complete

This may be a limitation in the type system, but thought I'd drop this proposal here. The idea here is that there should be some way of expressing that P is an object with keys that are a subset of the keys of T, then those keys that are missing on P from T are required to be supplied as U.

interface IComplete {
    a: string;
    b: string
}

function partial<T, P extends Partial<T>>(defaults: P) {
    return function<U extends MissingFrom<T, P>>(remaining: U) {
        const complete: T = { ...defaults, ...remaining };
        return complete;
    }
}

const curried = partial({a:"foo"});
const bar: IComplete = curried({b:"bar"});
const baz: IComplete = curried({b:"baz"});

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Proposal: ValueOf

It's a common question and not many know how to do it: https://stackoverflow.com/a/49286056/64949

type ValueOf<T> = T[keyof T];

type Foo = {a: string, b: number};

type ValueOfFoo = ValueOf<Foo>;
// string | number

The code is simple, but remembering the syntax is not. It would also be nice to have it as few know it's possible at all.

Real-world use-case: https://github.com/goodmind/FlowDefinitelyTyped/blob/333ce3a4273848326bfc43827eb4e7aa9a9d7441/types/react-native-vector-icons/FontAwesome5.d.ts


We could also consider instead adding a more powerful version that optionally supports picking the keys to get value from:

type ValueOf<T, K extends keyof T = keyof T> = T[K];

type Foo = {a: string, b: number: c: boolean};

type ValueOfFoo = ValueOf<Foo, 'a' | 'c'>;
// string | boolean

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.