Last active
July 19, 2022 22:15
-
-
Save lzehrung/cccd76da83a063146771f1f5b69975da to your computer and use it in GitHub Desktop.
type-checked property name string literals - https://www.typescriptlang.org/play?#code/PTAEEsDsGcAdwE4FMAmoBGBPUALALnrNAFwjQDGOkS4KSk6AhpQHQDm4e6A9twNbQW4bsDyZYSCgnCw8AWnK8+PfsEWQ89PMEiMAtkm4AzOdwkJGebghb49AGwBQj4ACpXoAKIwArslB4OEig0HjSkGygAG6M9j7B4NCgjNGxtKCwCGZICGKgugagxgHiwQAGACploK7AjkY+kOR4wpAZWbAAcvpIADwVAHwAFAVIxKB8SJjFFQCU46HhkQDejqDroMh…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inspired by https://schneidenbach.gitbooks.io/typescript-cookbook/content/nameof-operator.html | |
/** Ensure the string value is a valid property name of type `T` */ | |
function propName<T>(name: keyof T): string { | |
return name.toString(); | |
} | |
/** Ensure the string value is a valid property name of instance of type `T`. */ | |
function propOf<T>(instance: T, name: keyof T): string { | |
return propName<T>(name); | |
} | |
interface MultimediaDirectory { | |
name: string; | |
path: string; | |
} | |
const compiles1 = propName<MultimediaDirectory>('name'); | |
const fails1 = propName<MultimediaDirectory>('nameddd'); | |
const instance: MultimediaDirectory = { | |
name: 'My Documents', | |
path: 'C:\\My Documents' | |
}; | |
const compiles2 = propOf(instance, 'name'); | |
const fails2 = propOf(instance, 'wrong'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment