Open11

TypeScript

みつよしみつよし

文字列入力のvalidation

https://github.com/mitsuyoshi-yamazaki/AntOS/blob/ff2e4b100f6e0c9d90a2748d5e869c6e0e946d0e/src/os/infrastructure/console_command/utility/argument_parser.ts

// "int_key=32 string_key=hoge"

try {
  const someInt = arguments.int("int_key").parse()
  const someOptionalString = arguments.string("string_key").parseOptional()
  ...
} catch (error) {
  return error
}
// 以前のコード
      const keyValueArgs = new Map<string, string>()
      args.forEach(arg => {
        const [key, value] = arg.split("=")
        if (key == null || value == null) {
          return
        }
        keyValueArgs.set(key, value)
      })

      const rawCount = keyValueArgs.get("count")
      if (rawCount == null) {
        return "Missing count argument"
      }
      const count = parseInt(rawCount)
      if (isNaN(count) === true) {
        return "count is not a number"
      }
みつよしみつよし

返り値をGenericにするには?

JSにトランスパイルされる段階で型情報は消滅するので基本できない

function some<T>(): T

case hoge = some<Hoge>()

you can add a generics type to the method signature, but the compiler has no way of inferring the type
https://stackoverflow.com/a/37386570


こんな感じ

type ReturnTypeSpecifier = "string" | "number" | "boolean"
type ReturnType<T extends ReturnTypeSpecifier> = T extends "string" ? string :
  T extends "number" ? number :
  T extends "boolean" ? boolean :
  never

const ValueGetter: { [K in ReturnTypeSpecifier]: () => ReturnType<K> } = {
  string(): string {
    return ""
  },
  number(): number {
    return 0
  },
  boolean(): boolean {
    return false
  },
}

function getValue<T extends ReturnTypeSpecifier>(typeSpecifier: T): ReturnType<T> {
  const getter = ValueGetter[typeSpecifier] as (() => ReturnType<T>)
  return getter()
}

inferという関連項目があるらしいのであとで調べる

みつよしみつよし

Generic Argument

export type IterableArgumentType = "string" | "int"
export type IterableArgument<T extends IterableArgumentType> = T extends "string" ? StringArgument : T extends "int" ? IntArgument : never

function parseList<T extends IterableArgumentType>(argumentType: T): IterableArgument<T> {
  ...
}

const a = parse("string") // StringArgument
const b = parse("int") // IntArgument

https://github.com/microsoft/TypeScript/issues/13995
https://github.com/microsoft/TypeScript/issues/20375

修正されている?
https://github.com/microsoft/TypeScript/pull/43183