sotnikov-link / ts-keyof

Use variable name as a string over key in object. Little alternative to ts-nameof with zero-configs, but works in runtime! It's works good with JS-projects too.

Home Page:https://www.npmjs.com/package/ts-keyof

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Name of properrty

scinfu opened this issue · comments

Can I access to name property of class or interface?
like:

import { keyof } from "ts-keyof"
interface IModel {
  id: string
  name: string
}
console.log("Name of property",keyof(IModel.name)))

@scinfu

It's not possible, because IModel is TypeScript Interface. TypeScript Entities doesn't exist in runtime.

I can add keyof<IModel>("name") that will be give you "Name of property". Do you want it?

@sotnikov-link Yes, if the name "name" will wrong ES will detect the error?
es: keyof<IModel>("namex")

@scinfu if you use function below then TypeScript gives error for your case:

function getKeyOf<T extends object>(keyName: keyof T) {
  return keyName;
}

interface IModel {
  id: string
  name: string
}

getKeyOf<IModel>("name") === "name" // 👍

getKeyOf<IModel>("wrongKey") // 👎  Argument of type '"wrongKey"' is not assignable to parameter of type 'keyof IModel'.(2345)

TypeScript Play

This function doesn't work for TypeScript Refactoring so I don't want add this function in package ts-keyof.

@sotnikov-link nice.
Thank you