English 中文(简体)
如何给出数字不是零?
原标题:How to give the type of number that is not zero?

我很难确定<代码>Result的类型,例如:

<代码>Result应为以下模式之一:

type Result<Some> = { code: 0; some_result: ...}
// or
type Result = { code: NonZero; message: string}

如何分类?

或许这个问题可以分为:

  1. implement NonZero (p.s. Exclude<number, 0> does not work)
  2. give typing to the generic Result

Updates

我写了以下工作纲要:

type Result<TCode extends number, T extends {} = {}> = TCode extends 0
  ? { code: 0; } & T
  : { code: TCode; reason: string };

type SomeResult = {some_result: string}

function getSomeResult(): Result<0 | -1 | 6007 | 114514, SomeResult> {
  return {
    code: 0,
    some_result:   
  }
}

const result = getSomeResult()

switch (result.code) {
  case 0:
    // this is wrong: reason should be void
    result.reason
    // this is ok:
    result.some_result
    break
  default:
    // this is ok: there s always a reason when code is non-zero
    result.reason
}

现在,STS汇编商可以推断其他财产无效,但我需要把所有可能的非零件印成“代码<>/代码>的类型参数。

如何分类<代码>NonZero

问题回答
enum Codes {
    Pass,
    Foo,
    Bar
}

type Result<Code extends Codes, Some=undefined> = Code extends Codes.Pass ? { code: Codes.Pass; some: Some} 
  : { code: Exclude<Codes,Codes.Pass>; message: string}

const r0: Result<0, {name:string}> = { code: 0, some:{name: ""} };
const r1: Result<1> = { code: 1, message:"foo" };




相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签